Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a UILabel as subview of UIButton doesn't trigger button action

I have a UIButton and I am adding a subview to the UIButton which is a UILabel. When I tap on the UILabel the action of the button doesn't get triggered. Is there an easy fix so that the touch event gets passed to the UIButton when the UILabel is tapped?
I am thinking of adding a gesture recognizer to the UILabel which then triggers the action of the UIButton, not sure if there's a much more simpler way.

like image 482
adit Avatar asked Sep 05 '12 22:09

adit


2 Answers

You can probably just disable user interaction to your label.

_yourLabel.userInteractionEnabled = NO;
like image 185
rooster117 Avatar answered Oct 08 '22 09:10

rooster117


try this,

- (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");
}
like image 36
Venk Avatar answered Oct 08 '22 08:10

Venk