Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UIButton's action does not called

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?

like image 759
Anastasia Avatar asked Dec 22 '25 10:12

Anastasia


2 Answers

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.

like image 196
tkanzakic Avatar answered Dec 24 '25 00:12

tkanzakic


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.

like image 36
fatuous.logic Avatar answered Dec 23 '25 23:12

fatuous.logic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!