cannyboy
cannyboy

Reputation: 24426

Making a custom class's buttons trigger the parent class

I've got a UIViewController called "MainViewController" which uses a custom class 'CustomController' to control one of it's sub-views. The custom class instantiates UIButtons in code. How would I get these buttons to trigger methods in the MainViewController?

Upvotes: 1

Views: 248

Answers (1)

Besi
Besi

Reputation: 22939

I think delegation is the way to go there.

  1. Define the protocol CustomControllerDelegate inside CustomController.h with a method like this for example:

    - (void) customControllerButtonPressed(id)sender; // BTW: you can use `CustomController` instead of `id` if you make a forward declaration for this class
    
  2. Add a delegate property and synthesize it in the .m file

    @property (assign) id<CustomControllerDelgate> delegate;
    
  3. Now when your button is pressed you simply call the delegate:

    [self.delegate customControllerButtonPressed:self];
    
  4. In your MainViewController you make it conform to the specified protocol and set the CustomControllers delegate like so:

    CustomViewController *customVC = [[CustomViewController alloc] init];
    customVC.delegate = self;
    
  5. Now when the button is pressed, the MainViewController's implementation of the specified method is called.

Upvotes: 3

Related Questions