如何将单元格传递给tableView Swift 3中的函数

use*_*776 3 uitableview swift3

我想将一个单元格作为参数传递给函数 datePickerChanged(sender: UIDatePicker)

以下是代码的一部分,我想在其中实现这一点,有人可以建议我如何实现吗?

class DailyTimesTVC: UITableViewController {

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell

        cell.datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)
    }


    func datePickerChanged(sender: UIDatePicker){
        // Here I would like to access the cell
    }

}
Run Code Online (Sandbox Code Playgroud)

vad*_*ian 7

我建议使用回调闭包

  • DailyTimesTableViewCell创建一个callback传递UIDatePicker实例的变量中

    var callback : ((UIDatePicker) -> ())?
    
    Run Code Online (Sandbox Code Playgroud)
  • DailyTimesTableViewCell添加观察者awakeFromNib

    datePicker.addTarget(self, action: #selector(datePickerChanged), for: .valueChanged)
    
    Run Code Online (Sandbox Code Playgroud)
  • DailyTimesTableViewCell添加操作方法中调用回调

    func datePickerChanged(sender: UIDatePicker) {
       callback?(sender)
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • DailyTimesTVCcellForRow指定回调关闭

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = Bundle.main.loadNibNamed("DailyTimesTableViewCell", owner: self, options: nil)?.first as! DailyTimesTableViewCell
        cell.callback = { datePicker in
            // do something with the date picker
        }
        return cell
    }
    
    Run Code Online (Sandbox Code Playgroud)

是否有任何特殊原因需要为电池使用额外的笔尖?您可以直接在Interface Builder的表视图中创建多个单元格。