简体   繁体   中英

UIButton unresponsive when created programmatically and added to uiimageview

I have the following code in my viewDidLoad method. This is a uiviewcontroller with scrollview and page controller.

I have the following code which creates the views from an array puts a button on the 3rd page:

 for (int i = 0; i < imageNames.count; i++) {
CGRect frame;
frame.origin.x = self.scrollView.frame.size.width * i;
frame.origin.y = 0;
frame.size = self.scrollView.frame.size;

UIView *subview = [[UIView alloc] initWithFrame:frame];

UIImageView *myImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0.0,0.0,self.view.frame.size.width,self.view.frame.size.height)];

myImageView.image=[UIImage imageNamed:[imageNames objectAtIndex:i]];

[subview addSubview: myImageView];


UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[button addTarget:self 
           action:@selector(doSomething:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Show View" forState:UIControlStateNormal];

if(i == 1){
[myImageView addSubview:button];
}
[self.scrollView addSubview:subview];

}

I have an ibaction that will dismiss this view as it modal view: -(IBAction)doSomething:(id)sender{ [self dismissModalViewControllerAnimated:YES]; }

The problem is that this button is unresponsive. It doesn't even highlight when touch let alone call the doSomething method.

What am I doing wrong?

Note sure if this is the issue but probably.

From the UIImageView docs:

New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.

Posted for the benefit of future searchers...

If enabling the userInteractionEnabled property of the UIImageView hadn't worked, another thing to look at is whether the UIButton's view is outside the frame of its superview.

When an object's view is outside the frame of its superview, it will appear to the user but it will not be able to receive touch events.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM