Swift custom xib delegate

MattBlack

I am attempting to create a reusable date picker view. When the user presses the 'DOB' button the date picker xib is displayed. I am wanting to pass back to the ViewController the date which is selected.

When trying to implement a delegate method to achieve this I get an "unexpectedly found nil" on the below line:

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

How can I use a delegate to pass back the date selected in the custom view to the ViewController it is presented in?

The 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)
    }

}

The Custom xib class:

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)")
        }

    }
Sh_Khan

You need to set the delegate

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

//

also it's supposed that you only need the date , because self should be deallocated as you'll remove the picker view from it's parent after getting the date

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)")
   }

}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related