Reputation: 3246
I have read some explanations around here on why this tends to happen but I cannot figure out a fix for my case, which might be super easy.
I have a UITableViewController
which has 2 sections and 20 rows in each section.
I want to add a UISwitcher
in the second row so I've implemented the following:
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? SettingsCell else {
return UITableViewCell()
}
switch indexPath.row {
case 2: cell.addSwitcher()
default: break
}
return cell
}
Everything works as expected until I scroll up and down, and then I'll have switchers in every row after a while.
Is there a way to release or perform a cleanup in the dequeueReusableCell
or am I missing something here?
Here's my addSwitcher()
function
public func addSwitcher() {
accessoryView = switcher
switcher.addTarget(self, action: #selector(switcherDidChange(switcher:)), for: .valueChanged)
hasSwitcher = true
}
Upvotes: 0
Views: 88
Reputation: 100549
For sure this is because of cell dequeing , that's when you set it for the that cell and scroll , other shown cells below it get that same cell from dequeueReusableCell
, so you need to assign a nil to accessoryView
to clear any previous view assigned to it
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as! SettingsCell
cell.accessoryView = nil
you can also override prepareForReuse
Upvotes: 1