Swift自定义xib委托

时间:2018-07-04 19:38:12

标签: swift

我正在尝试创建可重用的日期选择器视图。当用户按下“ DOB”按钮时,将显示日期选择器xib。我想将选择的日期传回ViewController。

当尝试实现委托方法来实现此目标时,我在下一行得到“意外找到nil”:

  

delegate.myModularDidFinish(控制器:自我,日期:“(datePicker.date)”)

如何使用委托将自定义视图中选择的日期传回给其显示的ViewController?

ViewController:

    class ViewController2: UIViewController, MyModalDelegate2 {

    @IBAction func dobButton(_ sender: UIButton) {

        let allViewsInXibArray = Bundle.main.loadNibNamed("MyModalVC2", owner: self, options: nil)
        let dobView = allViewsInXibArray?.first as! UIView
        self.view.addSubview(dobView)
    }
    func myModularDidFinish(controller: MyModalVC2, date: String) {
        print(date)
    }

}

自定义xib类:

protocol MyModalDelegate2 {
    func myModularDidFinish(controller: MyModalVC2, date: String)
}

    class MyModalVC2: UIView {

        var delegate: MyModalDelegate2! = nil

        @IBOutlet weak var datePicker: UIDatePicker!
        @IBAction func datePicker(_ sender: Any) {

            delegate.myModularDidFinish( controller: self, date: "\(datePicker.date)")
        }

    }

1 个答案:

答案 0 :(得分:1)

您需要设置代表

let allViewsInXibArray = Bundle.main.loadNibNamed("MyModalVC2", owner: self, options: nil)
let dobView = allViewsInXibArray?.first as! MyModalVC2
dobView.delegate = self
self.view.addSubview(dobView)

//

还假定您只需要日期,因为self应该被释放,因为您将在获取日期后从其父视图中删除选择器视图

protocol MyModalDelegate2 {
    func myModularDidFinish(date: String)
}

class MyModalVC2: UIView {

   var delegate: MyModalDelegate2?
   @IBOutlet weak var datePicker: UIDatePicker!
   @IBAction func datePicker(_ sender: Any) {
       delegate?.myModularDidFinish(date: "\(datePicker.date)")
   }

}