【问题标题】:switch change on tableview row affecting other rows在影响其他行的 tableview 行上切换更改
【发布时间】:2016-08-07 14:18:50
【问题描述】:

我有以下表格视图单元格:

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
}

【问题讨论】:

  • 这是提示,tableView.dequeueReusableCellWithIdentifier() dequedCells 正在制造问题。
  • @satheeshwaran 我怎么能解决这个问题?
  • 因此,如果您在第 2 行切换开关,它是否会影响其他任何事情,还是只会在第 1 行发生??
  • 我有一个类似的问题,通过跟踪数组中的相关单元格来解决。看看这里的答案:stackoverflow.com/questions/34369939/…
  • @satheeshwaran 只是第 1 行总是影响最后一行

标签: ios swift uitableview uiswitch valuechangelistener


【解决方案1】:

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

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

【讨论】:

  • 最初我的 configureForQuestion 函数中有 questionAnswer.on = false ,但这会导致一个问题,如果我打开开关并向下滚动 tableview 并返回,开关将重置为假的:(
  • 已修复 - 需要将 questionAnswer.on = data.answer 放入我的 configureForQuestion 函数中!
  • 不错!批准的答案?
  • 如果你改变它我可以批准它! self.questionAnswer.on = false 是错误的,因为当它们被滚动出视图并在之后重新加载时,它会将打开的开关重置为 false
【解决方案2】:

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

您能否展示您的代码,说明您如何设置answers 中的值?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 2019-01-19
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    相关资源
    最近更新 更多