UIButton with custom view - addTarget:action:forControlEvents: does not work

Sagrian picture Sagrian · May 8, 2013 · Viewed 26.7k times · Source

My button is as follows

  1. Created label1
  2. Created label2
  3. Created customView (UIView)
  4. Added label1 and label2 on custom view
  5. Created myCustomButton(UIButton)
  6. Added customView on myCustomButton

I have already done userInteractionEnable for custom_View, label1 and label2.

Then added

[myCustomButton addTarget:self action:@selector(OnButtonClick:) forControlEvents:UIControlEventTouchUpInside];

And

-(void)OnButtonClick:(UIButton *)sender
{
}

But above function is never called even when I touch the button. Any solution?

Answer

Dipen Panchasara picture Dipen Panchasara · May 8, 2013

Just a minor problem with your code my friend, you just need to add only one following line to your code, forget to setUserInteractionEnabled:NO to UIView it will allow you to click the button

UILabel *lbl1 = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
[lbl1 setText:@"ONe"];
UILabel *lbl2 = [[UILabel alloc] initWithFrame:CGRectMake(0, 30, 100, 30)];
[lbl2 setText:@"Two"];

UIView * view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 130)];
[view setUserInteractionEnabled:NO];

[view addSubview:lbl1];
[view addSubview:lbl2];

UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn addSubview:view];
[btn setFrame:CGRectMake(0, 0, 200, 130)];
[btn addTarget:self action:@selector(click) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:btn];

Click Method

-(void)click
{
    NSLog(@"%s",__FUNCTION__);
}