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!
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With