I have a non-scrollable TableView. I want its height to be determined by the number of entries. To make this work I have used the height constraint (= CGFloat(data.count) * tableView.rowheight) of the TableView in the code. Is this good practice?
I noticed when I delete the last row of the TableView, it more or less skips the animation. Is this because the height of the table is adjusted faster than the animation needs? How can I solve this problem?
var data = [1,2,3,4,5,6,7,8,9,10]
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var tableViewHeight: NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = 50
tableViewHeight.constant = CGFloat(data.count) * tableView.rowHeight
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
cell.textLabel?.text = "\(data[indexPath.row])"
return cell
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
data.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: .automatic)
self.tableViewHeight.constant = CGFloat(self.data.count) * self.tableView.rowHeight
}
}
override func setEditing(_ editing: Bool, animated: Bool) {
super.setEditing(!isEditing, animated: true)
tableView.setEditing(!tableView.isEditing, animated: true)
}
}