ios - UITableViewCell 每 5 个单元格重复一次(在标记为重复之前,请阅读整个任务)

标签 ios swift uitableview custom-cell

(在你标记为重复之前,你必须阅读整个问题,我发布这个是因为我没有找到相关和适当的解决方案也需要快速解决方案)

我已经创建了一个演示项目,并从自定义单元格上的数组中加载并显示了名称和区域。 我注意到在每第 5 个单元格之后意味着第 6 行重复第 0 个单元格的内容 例如

演示代码如下

class demoTableCell: UITableViewCell {
    @IBOutlet var name : UILabel!
    @IBOutlet var area : UILabel!
}

extension ViewController:UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrDemo.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        var cell : demoTableCell = demoTable.dequeueReusableCell(withIdentifier: cellIdentifier)! as! demoTableCell

            cell.name.text = (arrDemo.object(at: indexPath.row) as! NSDictionary).value(forKey: "Name") as? String
            cell.area.text = (arrDemo.object(at: indexPath.row) as! NSDictionary).value(forKey: "Area") as? String

            if indexPath.row == 0{
                cell.name.isHidden = true
            }

        return cell
    }

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

    }
}

当我隐藏第 0 个单元格上的第一个标签时,我发现第 6 行也受到第 0 个单元格的已实现功能的影响。这意味着还隐藏了每第 6 个单元格的 label1,因为我附上了下面的屏幕截图,这样您就可以得到确切的问题(仅当表格 View 可滚动时才会发生此问题)

enter image description here enter image description here

因为我已经尝试从 this link 解决这个问题也遇到了同样的问题,找不到合适的解决方案,我被困在这里。

最佳答案

单元格被重用,您必须确保每个 UI 元素都设置为已定义的状态。

您正在使用 if 子句,但没有 else 大小写或默认值。

简单的解决方案:

只是替换

 if indexPath.row == 0 {
    cell.name.isHidden = true
 }

 cell.name.isHidden = indexPath.row == 0

这会将 hidden 属性始终设置为已定义状态。


还有通常的不要

  • 不要在 Swift 中使用 NSDictionary
  • 不要 valueForKey 除非你真的需要 KVC(实际上在这里你不需要)。

关于ios - UITableViewCell 每 5 个单元格重复一次(在标记为重复之前,请阅读整个任务),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47093236/

相关文章:

ios - Xcode 项目卡住 "Compiling Swift source files"

swift - 删除 UITableView 的最后一行时崩溃

ios - UITableView 中单元格之间的大间隙,iOS 错误?

ios - Unicode不间断空格在标签末尾被删除

ios - 以编程方式在 swift 中为 tableview 部分索引设置框架

javascript - 文本字段不会自动缩放焦点 [JQuery/Javascript]

ios - 使用 XHFaceMaskSDKSimple 在检测到的面部上设置 UIImage,无法添加演示中静态添加的图像

ios - 尝试符合 WCSessionDelegate 时使用未声明的类型错误

swift - 绕过 WatchKit 中的 playHaptic 预定义案例

swift - 如何在取消选择 UITableView 中的行时从数组中删除项目