Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIButton inside UIImageView does not respond to taps

I have a scroll view, which has an image view with an image as a subview, and the image view has a UIButton as one of its subviews. The problem is, I am not able to click on the button. I can SEE the button, but I cannot tap on it.

Can someone tell me what is it that I am messing up? Any help is greatly appreciated! Thanks!

Below is the code:

scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];     imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"img.jpg"]]; scrollView.delegate = self; self.view = scrollView;  // add invisible buttons [self addInvisibleButtons]; [scrollView addSubview:imageView]; 

addInvisibleButtons has the following code:

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect]; [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents]; [button setTitle:@"point" forState:UIControlStateNormal]; button.frame = CGRectMake(0.0, 0.0, 40.0, 40.0); [self.imageView addSubview:button]; 
like image 557
Ravi Avatar asked May 28 '11 21:05

Ravi


People also ask

What is the difference between a UIImage and a UIImageView?

UIImage contains the data for an image. UIImageView is a custom view meant to display the UIImage .


2 Answers

UIImageView has userInteractionEnabled set to NO/ false by default.

You are adding the button as a subview to the image view. You should set it to YES / true.

like image 134
Deepak Danduprolu Avatar answered Sep 25 '22 03:09

Deepak Danduprolu


May I ask why are you adding invisible UIButtons to UIImageView?

Seems like a bad practice, notice Interface Builder doesn't allow you to add UIButton inside them.

If you want an image with touch handling, you can:

UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom]; [button addTarget:self action:@selector(buttonHandler) forControlEvents:UIControlEventAllEvents]; [button setTitle:@"point" forState:UIControlStateNormal]; [button setImage:[UIImage imageNamed:@"img.jpg"] forState:UIControlStateNormal]; [button setFrame:CGRectMake(0.0, 0.0, 40.0, 40.0)];  [scrollView addSubview:button]; 
like image 38
Desdenova Avatar answered Sep 22 '22 03:09

Desdenova