如何为自定义UIButton添加点击动作?

4

我有一个子类UIButton,它加载了一个Nib:

@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文件上。但我不知道哪个视图首先响应了点击事件?我该如何设置按钮为首要响应点击事件?
我错过了什么?
您可以在这里找到完整的Xcode项目:
https://www.dropbox.com/s/zjhwy7jm8jcywz4/blabla1_111.zip 谢谢!

代码看起来很好。如果您省略XIB并改为完全以编程方式创建按钮,会怎样呢? - user529758
1个回答

2

禁用视图的子视图,因为它们会捕获触摸事件。
可以在xib中设置userinteraction enabled属性或通过代码实现:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接