ios - 从 TableViewCell 到 UIViewController 的协议
问题描述
我有一个表格和一个自定义单元格。我从表中获取值并将它们传递给单元格。从单元格中,我必须将这些值传递给 VC。但是如果单元格中有这些值,那么在 VC 上它们已经 = nil
class CloseMonthTableViewCell : UITableViewCell {
var delegate: StatusCloseMonthDelegate?
@IBAction func setStatus(_ sender: Any) {
self.delegate?.setStatus(status: 2, empId: empId ?? 0)
}
}
protocol StatusCloseMonthDelegate: class {
func setStatus(status: Int, empId: Int)
}
DialocVC
class ApproveDialogView: UIViewController {
var cellDelegate = CloseMonthTableViewCell()
var status: Int?
var empId: Int?
override func viewDidLoad() {
super.viewDidLoad()
cellDelegate.delegate = self
}
@IBAction func setStatus(_ sender: Any) {
print(status,empId) // nil and nill Why are they = nil?
}
}
extension ApproveDialogView: StatusCloseMonthDelegate {
func setStatus(status: Int, empId: Int) {
self.status = status
self.empId = empId
}
}
解决方案
多读一些关于如何使用协议/委托模式的文章。
class ApproveDialogView: UIViewController {
// get rid of this line!
//var cellDelegate = CloseMonthTableViewCell()
var status: Int?
var empId: Int?
override func viewDidLoad() {
super.viewDidLoad()
// get rid of this line!
//cellDelegate.delegate = self
}
@IBAction func setStatus(_ sender: Any) {
print(status,empId) // nil and nill Why are they = nil?
}
}
我假设您也有UITableViewDataSource
and 的扩展名UITableViewDelegate
:
extension ApproveDialogView: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CloseMonthTableViewCell
// normal cell settings
// set the cell's delegate here!
cell.delegate = self
return cell
}
}
推荐阅读
- javascript - 在php中的表中添加onclick事件
- wordpress - 如何使用 gform_product_info 更新重力表格上的总条目
- c# - 从 url MSBUILD xml 恢复 Nuget 包
- java - jQuery 终端 - 以字符串形式读取 Java 中的 shell 响应会在 jQuery 终端中显示奇怪的字符
- python - 嵌入时出错:无法将字符串转换为浮点数:'ng'
- wordpress - Woocommerce 只读计费字段 - 选择和单选字段
- c# - Entityframework为什么耦合表会得到重复值?
- symfony - 如何调试捆绑中的 DependencyInjection ?
- websphere - websphere application server 8.5.5 创建了很多到 ldap 的连接
- javascript - 到达带有锚点的页面时触发事件