I need to add multiple checkbox in my tableview cell , so that cell size automatically increase as per number of checkbox buttons at runtime. How can I do it ?
My custom cell
import UIKit
class checkboxCell: UITableViewCell {
@IBOutlet weak var txtLabel: UILabel!
@IBOutlet weak var backView: UIView!
@IBOutlet weak var checkBoxView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
My code for display cell with runtime adding checkbox with label
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
............
.................
if indbexpath.row == 4
{
var checkBoxcell = tableView.dequeueReusableCell(withIdentifier:"checkboxCell") as? checkboxCell
if checkBoxcell == nil{
let arrNib:Array = Bundle.main.loadNibNamed("checkboxCell",owner: self, options: nil)!
checkBoxcell = arrNib.first as? checkboxCell
}
checkBoxcell?.txtLabel.text = "Sample Checkbox"
let checkBoxArray = NSMutableArray(array:model.idnamemodelUI! as NSArray)
for i in 0..<checkBoxArray.count {
let checkbox = CheckBox(frame: CGRect(x: 10, y: i * 45, width: 30, height: 30))
checkbox.checked = false
checkbox.tag = "This is a label"
checkBoxcell?.contentView.addSubview(checkbox)
let label = UILabel(frame: CGRect(x: 60, y: i * 45, width: 200, height: 30))
label.textAlignment = .left
label.text = labelName
checkBoxcell?.contentView.addSubview(label)
}
return checkBoxcell!
}
............
.......
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableView.automaticDimension
}
func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
return 100 //66
}
Desired output looking for
Approach 1: Use a nested table, add another check box table inside the main table view cell and make the inner table dynamic (https://medium.com/@dushyant_db/swift-4-recipe-self-sizing-table-view-2635ac3df8ab).
Approach 2: Use the stack view. Add UIStackView in content view and give top, bottom, left, right constraint and bind the outlet with cell after that, use stack view property addArrangedSubview to add your chack box view into the stack view.
Approach 3 (Not recommended): In your code, you used a fixed size of check box view so, in heightForRowAt method calculate the height for cell and return calculated height. e.g. suppose check box count is 5 then the final height is (checkBoxCount * (fixedCheckBoxViewHeight + spaceBetweenTwoCheckBox))