How to connect delegate from custom class in xib? How to connect delegate from custom class in xib? swift swift

How to connect delegate from custom class in xib?


First thing you need to do is to add @objc in from of your protocol definition, so that it looks like:

@objc protocol DeletableImageViewDelegate {    ...}

You might ask why do you need to do this. It's because you want to add delegate property to the storyboard, and in order to set some property visible by storyboard, it must have @IBOutlet prefix, and that prefix requires it to be Objective C protocol.

So the next thing you want to do is change var delegate: DeletableImageViewDelegate? to

@IBOutlet var delegate: DeletableImageViewDelegate?

Now if you right click on the view in the interface builder you will get something like this, which means that we exposed our delegate property to the interface builder.Exposed property

If you try to connect it to file owner (for example UIViewController), it will not work because your file owner still doesn't implement that protocol. To implement it you need to write:

extension UIViewController : DeletableImageViewDelegate {    // Implementation}

After you do that, you should be able to connect delegate property to the view controller, thus receiving delegate method messages. In each case your file owner must implement the protocol.


I've created solution similar as in the comments. But I've also wanted not have to cast delegate every time and check for protocol implementation.

weak var delegate: MenuViewDelegate?@IBOutlet weak var _delegate: AnyObject? {    didSet {        if let d = _delegate {            if let d = (d as? MenuViewDelegate) {                delegate = d            } else {                print("ERROR: delegate does not implement \(d) MenuViewDelegate protocol")                d as! MenuViewDelegate            }        }    }}