Reputation: 1661
I am struggling with my UISwitch
in a custom TableViewCell
.
The switch in the UITableViewCell
adds the item from the cell to another array. However, I have noticed that when I change a switch it also changes other switches in other cells.
I believe the issue is with the TableView dequeueReusableCell
function.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "currencyCell") as? currencyCell else { return UITableViewCell() }
}
Upvotes: 1
Views: 696
Reputation: 3900
You have to store the switch's value somewhere "outside" the UITableviewCell
to be able to reset it to the last value that the specific switch was in that cell.
I recommend to save it from the cell (e.g. when UISwitch's
value changed) with a delegate pattern. Then set it from the tableView:cellForRowAt:
function after you dequed the cell.
Upvotes: 1
Reputation: 535
I also had the same problem. Asked a senior developer, and he suggested that because in the UITableView
cells are reused. When one changes the state of the first UISwitch
in the UITableView
to ON and scrolls down, the cell with the first switch is reused, hence some of the subsequent switches are displayed as ON by default.
Turning the first UISwitch
ON is not changing the state of other switches in the UITableView
. Instead, the first switch is being reused.
So, the solution to this would be to bind the UISwitch
in every cell with some data. As an example (pseudocode):
public class ABC: UITableViewCell
{
.
.
.
.
public void UpdateCell(bool switchStatus)
{
SwitchInCell.On = switchStatus
}
}
UpdateCell method is called from a class that inherits UITableViewSource
class.
(Note: I am from C# background and developing for iOS using Xamarin. So above pseudocode is in C#. But can be very easily transferred to Swift.)
I hope this helped.
Upvotes: 0