Search code examples
iosswiftdelegation

How to set up a delegate from the child class?


Things are working but I’m trying to improve on how they work ;)

Here’s my scenario:

I have a custom Button and the tap event is triggering a custom function in the ViewController. This is happening via a delegate and everything is working fine.

I’m using storyboards and control+click to create the outlet to the custom button, and then setting up the delegate inside the ViewController class, like:

@IBOutlet weak var myButtonInstance: MyButton!

override func viewDidLoad() {
    super.viewDidLoad()
    myButtonInstance.delegate = self
}

My question:

Is there a way to set up this delegation from inside the custom button class? I saw that in Swift there isn't a self.parent, and that's what I've been looking for:

(pseudo code)

on custom button initialization:
 self.delegate = self.parent

Solution

  • If I understand you correctly you want to get a reference to the controller from inside the button to set him as delegate!?

    Your UIButton is part of the view hierarchy - your ViewController however is not. There is not and further more should not be an easy way for an element of the View-part of an application to access its Controller-part. It should only communicate with the Controller through said delegate. Anything else would conflict with the MVC design pattern.

    In a logical term it although does not make sense to assign someone else to be a delegate for you. It should always be the delegate initiating the delegation process via assigning itself as delegate.