How to connect delegate from user class in xib?

I created a class "DeletableImageView" (.swift + .xib) that uses the protocol, which I defined as "DeletableImageViewDelegate", through a property that I called a delegate.

Example for clarity:

DeletableImageView.swift

protocol DeletableImageViewDelegate { func deleteImageWithTag(tag: Int!) -> (Bool) func addImageOnViewWithTag(tag: Int!) -> (Bool) ... } class DeletableImageView: UIView { var view: UIView! var delegate: DeletableImageViewDelegate? // Some random methods + some use of the delegate protocol methods ... } 

My problem is that now when I try to use my class in the controller from the linked .xib file (this means that I drag the view in the interface constructor and assign the DeletableImageView class to this view), I can not bind the delegate property (even if I declare this property as an IBOutlet).

What I want to do is directly associate the output of the view delegate with the "file owner" in .xib

The same thing you do when you link the data source and delegate it from the table directly in the .xib file.

But when I control-drag and drop, they will not join together.

Does anyone have an idea of ​​what is going on?

Thank you very much.

+6
source share
2 answers

First of all, you need to add @objc from the definition of your protocol so that it looks like this:

 @objc protocol DeletableImageViewDelegate { ... } 

You may ask why you need it. This is because you want to add the delegate property to the storyboard, and in order to set any property visible in the storyboard, it must have the @IBOutlet prefix, and for this prefix it must be the Objective-C protocol.

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

 @IBOutlet var delegate: DeletableImageViewDelegate? 

Now, if you right-click on a view in the interface builder, you will get something like this, which means that we have expanded our delegate property for the interface builder. Public property

If you try to connect it to the owner of the file (for example, UIViewController ), this will not work, because the owner of your file still does not implement this protocol. To implement it, you need to write:

 extension UIViewController : DeletableImageViewDelegate { // Implementation } 

After that, you can connect the delegate property to the view controller, thereby receiving delegate method messages. In each case, the file owner must implement the protocol.

+1
source

I created the same solution as in the comments. But I also did not need to delegate a delegate every time and check the 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 } } } } 
0
source

All Articles