Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make clickable UIButton over UIImageView?

I want to create a UIButton to display over an UIImageView. My code snippet is as shown below:

imageView = [[UIImageView alloc] initWithImage:image]; //initWithImage:image

imageView.userInteractionEnabled = YES; //to enable touch interaction with image



UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn setTitle:@"ClickMe" forState:UIControlStateNormal];
[btn.titleLabel setFont:[UIFont systemFontOfSize:16]];


 btn.frame = CGRectMake(340, 550, 70, 50);

[btn addTarget:self action:@selector(onClickHotSpotButton)   forControlEvents:UIControlEventTouchUpInside]; //it wasnt working


[imageView addSubview:btn];
[self addSubview:imageView]; 

My application displays button exactly on part of image where i want to but it doesn't responds to click image. Instead it does detect single tap as i log output on its detection. But i want this button to get clicked on selection and to perform some function.

Thanks in advance.

wahib

like image 310
Wahib Ul Haq Avatar asked Oct 27 '11 13:10

Wahib Ul Haq


3 Answers

try setting the userinteraction of the button enabled.

[btn setEnabled:YES];

Coz the UIImageView will set the userinteraction of the button disabled by default.

Else you could try this.Just change the last two lines.

Replace:

[imageView addSubview:btn];
[self addSubview:imageView]; 

with this:

[self addSubview:imageView];
[self addSubview:btn];

Make sure you add the imageview first and the button second as i have mentioned. else the button would b placed behind the imageview and would seems hidden.

like image 59
Shob-Z Avatar answered Sep 29 '22 01:09

Shob-Z


i tried this and it works for me.......

UIImageView * imageView = [[UIImageView alloc]init];
[imageView setImage:[UIImage imageNamed:@"image.jpeg"]];
[imageView setFrame:CGRectMake(10,10,300,300)];
[imageView setContentMode:UIViewContentModeScaleToFill];
[imageView setUserInteractionEnabled:TRUE];

UIButton * ButtonOnImageView = [[UIButton alloc]init];
[ButtonOnImageView setFrame:CGRectMake(135,120,60,30)];
[ButtonOnImageView setImage:[UIImage imageNamed:@"image.jpeg"] forState:UIControlStateHighlighted];
 [ButtonOnImageView setImage:[UIImage imageNamed:@"image2.jpeg"] forState:UIControlStateNormal];
[ButtonOnImageView addTarget:self action:@selector(OnClickOfTheButton) forControlEvents:UIControlEventTouchUpInside];

 [imageView addSubview:ButtonOnImageView];
 [self.view addSubview:imageView];
like image 41
alok kumar singh Avatar answered Sep 29 '22 01:09

alok kumar singh


  1. you have to add define button as custom.It will work for you.

    UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];

like image 40
Akshay Avatar answered Sep 29 '22 03:09

Akshay