在影响其他行的表视图行上切换更改

switch change on tableview row affecting other rows

我有以下 class 用于 table 视图单元格:

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
    }
}

这个单元格由一个标签和一个开关组成。目前,当我更改第一行的开关状态时,它也会更改最后一行。似乎没有其他行以这种方式连接。我对这个很困惑。

额外信息:

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
}

可能是您的 answers 数组没有您期望的数据。在调试器中打印出 answers 的值,并查看每个 answer 是否具有您期望的 indexPath.row

你能展示一下你如何在 answers 中设置值的代码吗?

您需要覆盖单元格中的 prepareForReuse 并重置您的 ui 元素数据。

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