Reputation: 694
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).
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!
Upvotes: 5
Views: 2710
Reputation: 4381
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;
}
Upvotes: 4
Reputation: 13686
The way I'd do it is set the value of addTarget
to self
.
[myButton addTarget:self
action:@selector(doSomething:)
forControlEvents:UIControlEventTouchUpInside]
This will look for the method doSomething
on the object that the target is added in. In this case, this would be the view controller.
Upvotes: 0