首页 > 解决方案 > 从 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
    }
}

标签: iosswiftclassvariablesprotocols

解决方案


多读一些关于如何使用协议/委托模式的文章。

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?
        
    }
}

我假设您也有UITableViewDataSourceand 的扩展名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
    }
}

推荐阅读