如何将tap动作添加到自定义UIButton?

时间:2012-12-09 13:03:20

标签: ios uibutton action customization programmatically-created

我有一个加载Nib的子类UIButton:

@implementation BlaButtonVC

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        NSArray *subViews = [[NSBundle mainBundle] loadNibNamed:@"BlaButton" owner:self options:nil];
        [self addSubview:subViews[0]];
    }
    return self;
}

@end

我可以将此按钮添加到视图中,如下所示:

// ViewController.m
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    BlaButtonVC *button = [[BlaButtonVC alloc] initWithFrame:CGRectMake(10, 10, 280, 44)];

    button.titleXLabel.text = @"Bls";
    button.descLabel.text = @"Kues";

    [button addTarget:self action:@selector(tap:) forControlEvents:UIControlEventTouchUpInside];

    [button becomeFirstResponder];

    [self.view addSubview:button];
}

-(IBAction)tap:(id)sender
{
    NSLog(@"sssss");
}

我的问题是点击:不会调用方法。也尝试使用普通的UIButton,它确实有效,所以它一定是自定义xib文件的问题,我真的不知道哪个视图首先响应了tap操作?如何将按钮设置为响应点击操作的按钮?

我错过了什么?

在这里你可以找到完整的xcode项目:
https://www.dropbox.com/s/zjhwy7jm8jcywz4/blabla1_111.zip

谢谢!

1 个答案:

答案 0 :(得分:2)

禁用视图的子视图,因为它们可以捕捉到触摸 在xib(userinteraction enabled)中或通过代码:

((UIView *)subViews[0]).userInteractionEnabled = NO;