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
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.
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];
you have to add define button as custom.It will work for you.
UIButton *Button = [UIButton buttonWithType:UIButtonTypeCustom];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With