【问题标题】:tableview persisting cell image after reloading重新加载后tableview保留单元格图像
【发布时间】:2017-07-06 01:22:23
【问题描述】:

我有一个带有单元格的表格视图,当被选中时,它会在所选单元格中显示一个图像,然后当再次选择该单元格时,该图像会消失,依此类推。当我按下提交按钮时,选定的单元格会被记住,并且表格视图会重新加载新数据。但是这样做时,所有新数据都会加载,但所选单元格图像仍然存在。我尝试在主队列上调用 tableView.reloadData() 但它仍然存在。当我多次按下提交按钮时,图像也仍然存在。

这是我的代码:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    return currentQuestion.answers.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

    return tableView.frame.height/CGFloat(currentQuestion.answers.count)
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    setSelectedArray()
    let cell: AnswersTableViewCell = tableView.dequeueReusableCell(withIdentifier: "answersTableViewCell") as! AnswersTableViewCell

    let text = currentQuestion.answers[indexPath.row]
    let isAnAnswer = currentQuestion.answerKeys[indexPath.row]

    cell.answerTextLabel.text = text
    cell.answerView.backgroundColor = UIColor.white.withAlphaComponent(0.5)
    cell.contentView.sendSubview(toBack: cell.answerView)

    return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    if let cell: AnswersTableViewCell = tableView.cellForRow(at: indexPath) as? AnswersTableViewCell {

        if cell.answerImageView.image == nil {

            cell.answerImageView.image = UIImage(named: "paw.png")
            selected[indexPath.row] = true

        } else {

            cell.answerImageView.image = nil
            selected[indexPath.row] = false

        }
    }
}

@IBAction func submitButtonWasPressed() {

    if questionNumber < questions.count - 1 {

        questionNumber += 1
        setCurrentQuestion()
        self.answersTableView.reloadData()
        self.view.setNeedsDisplay()
    }
}

任何帮助都会很棒。谢谢

【问题讨论】:

    标签: swift uitableview swift3


    【解决方案1】:

    您需要将图像设置回cellForRow 中的正确值。表格中的单元格在对reloadData 的调用之间被重用,并且由于您没有触摸 imageView,因此它保持其先前的值。在我看来你想要的:

    cell.answerImageView.image = selected[indexPath.row] ? UIImage(named: "paw.png") : nil
    

    tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) 内部。

    【讨论】:

    • 太棒了,我尝试了类似的东西但失败了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多