Search code examples
iosswiftuitableviewuiswitchvaluechangelistener

switch change on tableview row affecting other rows


I have the following class for a table view cell:

class QuestionCell: UITableViewCell {
    @IBOutlet weak var questionAnswer: UISwitch!
    @IBOutlet weak var questionLabel: UILabel!

    var data: Answer?

    func configureForQuestion(data: Answer) {
        print("configureForQuestion triggered")
        questionLabel.text = data.question
        self.data = data
    }

    @IBAction func questionAnswerChanged(sender: UISwitch) {
        data?.answer = sender.on
    }
}

This cell consists of a label and switch. Currently when I change the switch status for the first row, it is also changing for the last row. No other rows seem to be connected in this way. I'm pretty stumped on this one.

Extra info:

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return answers.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier(TableView.CellIdentifiers.QuestionCell, forIndexPath: indexPath) as! QuestionCell
    cell.configureForQuestion(answers[indexPath.row])
    return cell
}

Solution

  • You need to override prepareForReuse in the cell and reset you ui elements data.

    override func prepareForReuse() {
        self.questionLabel.text = nil
        self.questionAnswer.on = data?.answer
    }