【问题标题】:Table View Scrolling Causes Unexpected Results [closed]表视图滚动导致意外结果[关闭]
【发布时间】:2018-07-06 08:40:01
【问题描述】:

我的表格视图有一个隐藏图像,当用户完成关卡时,该图像对相关单元格可见。这个过程没有问题。

奇怪的是,当我上下滚动表格视图时,这个隐藏的图像开始随机出现在属于未完成级别的其他单元格上。

如果我离开视图控制器并返回,意外的会消失,如果我再次开始滚动,它们会回来。

此外,如果所有图像都被隐藏(意味着没有完成的关卡),滚动不会导致此问题。这是我使用的代码片段:

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

    let cell = tableView.dequeueReusableCell(withIdentifier: "customCell") as! CustomTableViewCell
    cell.cellView.layer.cornerRadius = cell.cellView.frame.height / 2
    cell.levelLabel.text = levels[indexPath.row]
    cell.lockingImage.image = UIImage(named: lockState[indexPath.row])

    if completeState[indexPath.row] == "true" {
        cell.completedImage.isHidden = false
    } 
    return cell
}

有什么想法吗?

【问题讨论】:

  • 听起来像是单元重用问题。但没有代码,谁能说得清?

标签: swift uitableview uiimageview


【解决方案1】:

假设你正在做:

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell

        cell.myImageView.isHidden = true

        return cell
    }

你应该做的是:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! MyTableViewCell
    if levels[indexPath.row].isLevelCompleted {
        cell.myImageView.isHidden = false
    } else {
        cell.myImageView.isHidden = true
    }
    return cell
}

这是因为您正在使单元格出列。这意味着 UITableView 将使用旧单元格。如果你主动更换单元格,你就可以走了。

【讨论】:

  • 谢谢 Onur,我忘了写“else”声明。现在它完美地工作了。
  • @EmreKurtaran 欢迎您,Emre。如果您还有其他问题,可以随时联系我
【解决方案2】:

您可能没有在单元格的prepareForReuse 函数中将图像可见性重置为false,这会导致在重复使用相关单元格时图像可见。

【讨论】:

    猜你喜欢
    • 2017-03-29
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多