添加UILabel作为UIButton的子视图不会触发按钮操作

时间:2012-09-05 22:43:09

标签: iphone objective-c ios ipad

我有一个UIButton,我正在为UIButton添加一个UILabel的子视图。当我点击UILabel时,按钮的动作不会被触发。是否有一个简单的解决方案,以便在点击UIButton时将触摸事件传递给UILabel? 我正在考虑向UILabel添加手势识别器,然后触发UIButton的操作,不确定是否有更简单的方法。

2 个答案:

答案 0 :(得分:5)

您可以禁用用户与标签的互动。

_yourLabel.userInteractionEnabled = NO;

答案 1 :(得分:4)

试试这个,

- (void)viewDidLoad
{
    [super viewDidLoad];
    UIButton *firstButton=[UIButton buttonWithType:UIButtonTypeRoundedRect];
    [firstButton setTitle:@"first" forState:UIControlStateNormal];
    firstButton.frame=CGRectMake(40, 70, 80, 80);
    [firstButton addTarget:self action:@selector(firstButtonClicked) forControlEvents: UIControlEventTouchUpInside];
    [self.view addSubview:firstButton];

    UILabel *label=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 80, 80)];
    label.text=@"hai";
    label.backgroundColor=[UIColor redColor];
    [firstButton addSubview:label];

}

-(void)firstButtonClicked {
    NSLog(@"first");
}