swift - 在表格视图中选择和取消选择行时发出执行功能
问题描述
注意:TableView 使用 JSON 填充,其结构包含值 codeNum
我需要根据是否选择或取消选择行来执行两个不同的功能,以下是我现有的选择机制:
class CheckableTableViewCell: UITableViewCell {
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
}
}
选择行时select()
需要运行,未选择行时unselect()
需要运行。在此之前,需要将行 codeNum 值分配给变量 tappedSelected:
structure = sections[indexPath.section].items
let theStructure = structure[indexPath.row]
tappedSelected = theStructure.codeNum
这如何实现到自定义类中?
解决方案
您可以使用闭包在选择/取消选择单元格时调用方法。
首先,closure
在你的中创建一个并用in方法CheckableTableViewCell
调用它,即true/false
setSelected(_:animated:)
class CheckableTableViewCell: UITableViewCell {
var handler: ((Bool)->())? //here....
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
self.accessoryType = selected ? .checkmark : .none
handler?(selected) //here....
}
//rest of the code....
}
接下来,在您的 中ViewController
,设置例如方法中的handler
值CheckableTableViewCell
,tableView(_:cellForRowAt:)
即
class VC: UIViewController, UITableViewDataSource {
//rest of the code...
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CheckableTableViewCell
cell.handler = {[weak self](selected) in
selected ? self?.select(indexPath) : self?.unselect()
}
return cell
}
func select(_ indexPath: IndexPath) {
let structure = sections[indexPath.section].items
let theStructure = structure[indexPath.row]
tappedSelected = theStructure.codeNum
}
func unselect() {
//add the code here...
}
}
这将解决您在选择或取消选择单元格时调用select()
或unselect()
方法的问题。
对于您的另一个要求,请说明您想在什么时候将codeNum
value 设置为tappedSelected
. 并且在哪里tappedSelected
存在,在ViewController
或在CheckableTableViewCell
。
推荐阅读
- firebase - Firestore:显示用户未注册的事件列表
- javascript - Prisma 迁移导致数据丢失
- python - 使用 asyncio 并发写入多个文件
- django - 使用 Django models.FileField 从内存中读取文件并在写入目录之前将其丢弃
- ui-automation - 使用空手道通过 Playwright 启动浏览器窗口的示例
- kivymd - Kivymd mapview 应用程序无法加载图像
- html - 复制单元格颜色并在 EMAIL 正文中发送
- javascript - 在 JS 中使用缩略图将背景更改为 Css
- c# - 未从所选目录运行的文件
- r - R:将数据框熔化 1 列并堆叠具有相同名称模式的其他列