Reputation: 3034
I have subclass of UIButton
:
@interface MyButton : UIButton
- (IBAction) buttonPressed:(id)sender;
@end
@implementation MyButton
- (void)awakeFromNib
{
NSLog(@"awake from nib");
}
- (IBAction) buttonPressed:(id)sender
{
NSLog(@"button pressed");
}
@end
I add a button in my parent xib, set it's class to MyButton, and connected it's action to First Responder
's method buttonPressed
.
When I start an application and load my parent xib with my button inside, than awakeFromNib
from MyButton class is called. But when I press the button, nothing happens. I was expecting that my method buttonPressed
from MyButton
class will be called.
I supposed, that my button's view is the first responder in responder chain, but apparently I do something wrong.
Could you please suggest something?
Upvotes: 3
Views: 3839
Reputation: 5499
If you want that your button always call the method declared add the code above to the awakeFromNib
method
[self addTarget:self action:@selector(buttonPressed:) forControlEvents:UIControlEventTouchUpInside];
and later when you added it to a view controller do not assign it a new action, this way it will always call your method.
Upvotes: 4
Reputation: 1160
Since you want to handle the action from the button code itself, you may have to override this method - (void)sendActionsForControlEvents:(UIControlEvents)controlEvents
and handle your event as if it was sent to your button;
Upvotes: 2
Reputation: 750
Depending on what you are doing with the button - there is no real need to make a subclass.
Here is some code how to make a simple button that triggers a method:
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[myButton setFrame:CGRectMake(10, 10, 100, 30)];
[myButton setTitle:@"Title" forState:UIControlStateNormal];
[myButton addTarget:self action:@selector(myMethod:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:myButton];
the add target bit tells the button to trigger the given selector when the user touches up inside the button (taps it). The target is the object that the selector is in.
Hope this helps, you should not need to subclass UIButton unless you have custom layouts or specific custom functionality for it.
Upvotes: 3