ios - 单击 UITableViewCell 时更新标签
问题描述
我有一个包含许多表格视图单元格的表格视图。当用户单击单元格时,我想更新单元格的标签文本。
这是我的表视图控制器类:
class MyTableViewController: UITableViewController {
var data = [Data]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
// Here I fetch and populate the data list
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "MyTableViewCell"
guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MyTableViewCell else {
fatalError("The dequeued cell is not an instance of MyTableViewCell.")
}
let cellData = data[indexPath.row]
cell.initialize(data: cellData)
return cell
}
}
这是我的表格视图单元格类:
class MyTableViewCell: UITableViewCell {
var data: Data?
@IBOutlet weak var nameLabel: UILabel!
func initialize(data: Data) {
self.data = data
if let cellName = data.name {
nameLabel.text = cellName
}
}
}
nameLabel
当用户单击表格视图单元格时,如何更改上述文本(为“已单击”)?
解决方案
毫无疑问,您可以通过不同的方式来处理这个问题,但这是我的建议:
实现 UITableViewDelegate 方法tableView(_:didSelectRowAt:)
和tableView(_:didDeselectRowAt:)
. 为表格视图中的单元格的数据模型添加一个selected
布尔值,并在选择/取消选择单元格时更新该布尔值的状态。
然后修改您的cellForRow(at:)
方法,使其使用selected
标志来决定在标签中显示什么。
最后,让您的tableView(_:didSelectRowAt:)
andtableView(_:didDeselectRowAt:)
方法告诉表格视图重新加载新选择/取消选择的单元格。
推荐阅读
- xml - 在 XSLT 1.0 中循环使用 XML 数据
- imagemagick - 在 ImageMagick 标签中转义 [0]
- typescript - 如何理解这个 TypeScript/ES6 函数的语法?
- c# - GraphQL json 解析器和 AllowSynchronousIO
- android - 如何修复“意外元素
在发现 “ 错误? - reactjs - 为什么 Laravel 视频流不起作用?我正在使用第三方包
- vim - 用 Vader 测试 vimdiff
- ruby - 是否可以在函数中同时为所有参数指定默认值?
- apache-spark - Spark DataFrame过滤器函数抛出Task not Serializable异常
- javascript - 如何使用核心ui模板在vue js中获取选定的值