Swift iOS - 如何在不重新加载数据的情况下更改已加载到屏幕上的所有可见单元格的 TableView 单元格属性?
Swift iOS -How to change TableView Cell Properties for All Visible Cells Already Loaded On Screen Without Reloading Data?
我正在使用 splitViewController,在主控端我有一个 tableView,在细节端我有将从所选单元格中显示的任何信息。
我从详细信息端向主控端发送通知,以更改单元格内已加载到屏幕上的文本标签的颜色(我不想重新加载)。
- 单元格首先加载黑色文本标签
- 当单元格仍在屏幕上时,会发送通知,我想将 textLabels 更改为浅灰色
- 当单元格仍在屏幕上时,发送了一个不同的通知,我想将 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
}
我怎样才能执行上述操作并立即访问所有可见单元格并更改它们的属性?
您可以访问 属性 visibleCells
UITableView
和 UICollectionView
。以下是您可以执行的操作的示例:
tableView?.visibleCells.forEach { cell in
if let cell = cell as? YourCell {
cell.changeTextLabelColorBackToBlack()
}
}
我正在使用 splitViewController,在主控端我有一个 tableView,在细节端我有将从所选单元格中显示的任何信息。
我从详细信息端向主控端发送通知,以更改单元格内已加载到屏幕上的文本标签的颜色(我不想重新加载)。
- 单元格首先加载黑色文本标签
- 当单元格仍在屏幕上时,会发送通知,我想将 textLabels 更改为浅灰色
- 当单元格仍在屏幕上时,发送了一个不同的通知,我想将 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
}
我怎样才能执行上述操作并立即访问所有可见单元格并更改它们的属性?
您可以访问 属性 visibleCells
UITableView
和 UICollectionView
。以下是您可以执行的操作的示例:
tableView?.visibleCells.forEach { cell in
if let cell = cell as? YourCell {
cell.changeTextLabelColorBackToBlack()
}
}