如何在不重新加载所有 UITableView 数据的情况下更新特定 UITableViewCell 中的标签?
How to update a label in a specific UITableViewCell without reloading all UITableView data?
我正在尝试刷新 UITableViewCell 中的标签,而不必刷新整个 table。这是为了制作一个计时器应用程序,我将每秒刷新一次 UITableView 中的标签(倒计时时)。
Link to a simulator screenshot of the table view
以前尝试过每秒重新加载整个UITableView的数据五次,但是这样导致滑动删除非常不一致,很难执行。我还没有成功更新个别行,所以我不知道这是否是一个可能的解决方案。
我找不到任何类似的问题,但如果你知道以前有人问过,请重定向我。
如有任何帮助,我们将不胜感激!
谢谢!
如果你能找到相应标签的索引,那么你就可以轻松获取单元格并访问标签,然后做任何你想做的事
let indexPath = IndexPath(row: 2, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
cell.YourLabel.backgroundColor = UIColor.green // write as per your requirement
}
Swift 中最有效的方法是回调闭包。它造成的开销比 protocol/delegate 或通知少得多。
- 运行 数据模型中的计时器。
在模型中声明一个回调属性
var updateLabel : ((String) -> Void)?
并在计时器触发时调用它
@objc func timerDidFire(_ sender: Timer) {
updateLabel?("New Value") // replace "New Value" with the actual value
}
在cellForRowAt
中分配一个闭包给updateLabel
属性来更新标签
let model = datasourceArray[indexPath.row]
model.updateLabel = { value in
cell.textLabel.text = value
}
在tableView:didEndDisplaying:forRowAt:
去掉闭包
let model = datasourceArray[indexPath.row]
model.updateLabel = nil
我正在尝试刷新 UITableViewCell 中的标签,而不必刷新整个 table。这是为了制作一个计时器应用程序,我将每秒刷新一次 UITableView 中的标签(倒计时时)。
Link to a simulator screenshot of the table view
以前尝试过每秒重新加载整个UITableView的数据五次,但是这样导致滑动删除非常不一致,很难执行。我还没有成功更新个别行,所以我不知道这是否是一个可能的解决方案。
我找不到任何类似的问题,但如果你知道以前有人问过,请重定向我。
如有任何帮助,我们将不胜感激! 谢谢!
如果你能找到相应标签的索引,那么你就可以轻松获取单元格并访问标签,然后做任何你想做的事
let indexPath = IndexPath(row: 2, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? YourTableViewCell {
cell.YourLabel.backgroundColor = UIColor.green // write as per your requirement
}
Swift 中最有效的方法是回调闭包。它造成的开销比 protocol/delegate 或通知少得多。
- 运行 数据模型中的计时器。
在模型中声明一个回调属性
var updateLabel : ((String) -> Void)?
并在计时器触发时调用它
@objc func timerDidFire(_ sender: Timer) { updateLabel?("New Value") // replace "New Value" with the actual value }
在
cellForRowAt
中分配一个闭包给updateLabel
属性来更新标签let model = datasourceArray[indexPath.row] model.updateLabel = { value in cell.textLabel.text = value }
在
tableView:didEndDisplaying:forRowAt:
去掉闭包let model = datasourceArray[indexPath.row] model.updateLabel = nil