简体   繁体   中英

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?

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.

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.

由于您希望处理按钮代码本身的操作,您可能必须覆盖此方法- (void)sendActionsForControlEvents:(UIControlEvents)controlEvents并处理您的事件,就像它被发送到您的按钮一样;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM