Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a method in a UIViewController from a UIButton in a subview

Still learning about Objective C and getting the structure right.

I have an iOS App with a UIViewController that has a defined method named "doSomething". In my view controller I have a view and in that view a number of UIButton that I create programmatically (see example below with one button).

enter image description here

Now when I press the button I want to call my method "doSomething". The way I currently do it is like this:

[myButton addTarget:nil 
             action:@selector(doSomething:)
     forControlEvents:UIControlEventTouchUpInside];

Since my target is nil it goes up the responder chain until it finds a method called "doSomething". It works, but it does not really feel right.

I have started to look into using @protocol but not really got my head around it. I have been looking at some tutorials but for me it is not clear enough. I have used protocols like for the table view controllers, but defining one is new for me.

Would it be possible to get an example for this specific case?

Thanks!

like image 555
Structurer Avatar asked Oct 11 '22 23:10

Structurer


1 Answers

As your target pass in the view controller and the method will be called on that object.

Edit:

[myButton addTarget:controller 
             action:@selector(doSomething:)
     forControlEvents:UIControlEventTouchUpInside];

Assuming that you have a variable called controller that is your UIViewController. If you don't have a reference to your controller then simply pass one to your view.

Edit2:

View interface:

@property (assign) UIViewController* controller;

View implementation:

@synthesize controller;

Controller:

- (void) viewDidLoad {
    [super viewDidLoad];
    someView.controller = self;
}
like image 97
skorulis Avatar answered Nov 24 '22 06:11

skorulis