Spooky Chen
Spooky Chen

Reputation: 25

ios swift - Why I tap a UISwitch ON and the other UISwitchs change ON simultaneously?

I inserted a UISwitch element in my custom UITableViewCell, and I have over 100 cells in my UITable.

It displays multiple UISwitch that I can tap which one is on and off in the UITable.

But I found something weird.

When I tap the first UISwitch, the 13rd, 26th, 38th, 51st, .... UISwitch changes its status simultaneously.

No matter which section they are, I change one UISwitch status, and another UISwitch changes.

The interval of those changed UISwitch are 11, 12, 11, 12, 11, 12............ elements.

I tap the 13rd UISwitch OFF, and the 1st, 26th, 38th, ..... UISwitch changes to OFF.

I tried to apply Segmented Control instead of UISwitch, and I get the same actions of those elements.

I write these code in my ViewController.

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{

        let cell : CardListCell = tableView.dequeueReusableCellWithIdentifier("RandomCardCell") as CardListCell
        var person = cardArray1[indexPath.item]
        cell.setCell(person.cardName, leaderName: person.leaderName, cardNo: person.cardNo, groupName: "")
        cell.countDelegate = self   
        //this is my delegate claimed in the Cell, and implemented in the View Controller 

        return cell
}

In my cell, I create a function to set values of the custom cell.

func setCell(cardName: String, leaderName: String, cardNo: Int, groupName: String)
{
    self.cardNameLabel.text = cardName
    self.leaderNameLabel.text = leaderName
    self.cardNo = cardNo
    self.groupName = groupName
}

I did nothing in the UISwitch action now.

 @IBAction func switchAction(sender: AnyObject) {

 }

Do I miss any thing when I set up my custom cell ??

I just want to tap one, and ONLY ONE UISwitch changes, not multiple ones change.

Upvotes: 0

Views: 1301

Answers (1)

Phillip Mills
Phillip Mills

Reputation: 31026

You need to set the switch either on or off in your cell before you return it from cellForRowAtIndexPath. If you only turn it on and then use a cell returned by tableView.dequeueReusableCellWithIdentifier, you're going to get the cached value when your old cell is re-used.

Upvotes: 0

Related Questions