代码之家  ›  专栏  ›  技术社区  ›  Lance Samaria

Swift iOS-如何在不重新加载数据的情况下更改屏幕上已加载的所有可见单元格的TableView单元格属性?

  •  1
  • Lance Samaria  · 技术社区  · 8 年前

    我使用的是splitViewController,在主界面我有一个tableView,在细节界面我有从所选单元格显示的任何信息。

    我从细节端向主端发送一个通知,在单元格内的文本标签已经加载到屏幕上后更改其颜色(我不想重新加载)。

    enter image description here

    1. 当单元格仍在屏幕上时,会发送通知,我想将文本标签更改为浅灰色

    enter image description here

    1. 当单元格仍在屏幕上时,会发送另一个通知,我想将文本标签改回黑色

    enter image description here

    一切都很好,但问题是我现在这样做,我只能单独改变每个可见细胞,但我想一次改变它们。如果有10个单元格,就会有很多代码,所以我知道必须有一种更有效的方法。

    @objc fileprivate func changeTextLabelColorToLightGray(){
    
            let indexPathZero = NSIndexPath(row: 0, section: 0)
            let cellZero = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
            cellZero.textLabel.text = UIColor.lightGray
    
            let indexPathOne = NSIndexPath(row: 1, section: 0)
            let cellOne = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
            cellOne.textLabel.text = UIColor.lightGray
    }
    
    @objc fileprivate func changeTextLabelColorBackToBlack(){
    
            let indexPathZero = NSIndexPath(row: 0, section: 0)
            let cellZero = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
            cellZero.textLabel.text = UIColor.black
    
            let indexPathOne = NSIndexPath(row: 1, section: 0)
            let cellOne = tableView.cellForRow(at: indexPathZero as IndexPath) as! MyCustomCell
            cellOne.textLabel.text = UIColor.black
    }
    

    1 回复  |  直到 8 年前
        1
  •  6
  •   Jeremy    8 年前

    visibleCells 对于 UITableView UICollectionView . 以下是您可以做的示例:

        tableView?.visibleCells.forEach { cell in
            if let cell = cell as? YourCell {
                cell.changeTextLabelColorBackToBlack()
            }
        }