Asking because all solutions available are for Swift 3. Also, I am dealing with a problem that when I scroll up and down after highlighting + selecting a row, new rows that appear with the same indexPath (after scrolling) will also be checked (but not highlighted).
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .none
}
}
Instead of change accessoryType
on didSelectRowAt
and didDeselectRowAt
methods, you should override and do it on setSelected(_:animated:) from your cell class.
class YourCellClass: UITableViewCell {
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
accessoryType = .checkmark
} else {
accessoryType = .none
}
}
}