简体   繁体   English

通过编程创建并添加到uiimageview时,UIButton无响应

[英]UIButton unresponsive when created programmatically and added to uiimageview

I have the following code in my viewDidLoad method. 我的viewDidLoad方法中包含以下代码。 This is a uiviewcontroller with scrollview and page controller. 这是带有滚动视图和页面控制器的uiviewcontroller。

I have the following code which creates the views from an array puts a button on the 3rd page: 我有以下代码从数组创建视图,并在第3页上放置一个按钮:

 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]; 我有一个ibaction,它将以模态视图关闭此视图:-(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. 当触摸更不用说调用doSomething方法时,它甚至不会突出显示。

What am I doing wrong? 我究竟做错了什么?

Note sure if this is the issue but probably. 知道这是问题,但可能。

From the UIImageView docs: UIImageView文档:

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. 如果要处理UIImageView的自定义子类中的事件,则必须在初始化对象后将userInteractionEnabled属性的值显式更改为YES。

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. 如果没有启用UIImageViewuserInteractionEnabled属性,则需要查看的另一件事是UIButton的视图是否在其超级视图的框架之外。

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. 当对象的视图超出其视图的范围时,它将显示给用户,但将无法接收触摸事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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