簡體   English   中英

Swift iOS-如何更改已在屏幕上加載的所有可見單元的TableView單元屬性,而無需重新加載數據?

[英]Swift iOS -How to change TableView Cell Properties for All Visible Cells Already Loaded On Screen Without Reloading Data?

我正在使用splitViewController,在主端,我有一個tableView,在詳細端,我有將從所選單元格顯示的任何信息。

在單元格已加載到屏幕上之后,我從明細端向主端發送通知以更改單元格內部的textLabel的顏色(我不想重新加載)。

  1. 單元格首先加載黑色textlabel的

在此處輸入圖片說明

  1. 當單元格仍在屏幕上時,會發送通知,我想將textLabels更改為lightGray

在此處輸入圖片說明

  1. 當單元格仍在屏幕上時,將發送其他通知,我想將textLabels更改回黑色

在此處輸入圖片說明

一切正常,但問題是我現在的工作方式,我只能分別更改每個可見的單元格,但我想一次更改它們。 如果有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
}

如何執行以上操作,訪問所有可見的單元格並立即更改它們的屬性,而不是分別更改?

您可以訪問UITableViewUICollectionView visibleCells屬性。 這是您可以做什么的示例:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM