【问题标题】:UIButton unresponsive when created programmatically and added to uiimageview以编程方式创建并添加到 uiimageview 时,UIButton 无响应
【发布时间】:2012-06-30 16:36:53
【问题描述】:

我的 viewDidLoad 方法中有以下代码。这是一个带有滚动视图和页面控制器的 uiviewcontroller。

我有以下代码,它从数组创建视图,在第三页上放置一个按钮:

 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];

}

我有一个 ibaction 会将该视图视为模态视图: -(IBAction)doSomething:(id)sender{ [自我dismissModalViewControllerAnimated:是]; }

问题是这个按钮没有响应。它甚至不会在触摸时突出显示,更不用说调用 doSomething 方法了。

我做错了什么?

【问题讨论】:

  • 代替IBActions 尝试使用-(void)doSomething
  • IBActions 代表 Interface Builder Action,但您的 not 使用 IB
  • @TheDeveloper IBAction 在 UIKit.h 中 #define'd 为 void
  • 我似乎无法在 Xcode 中阅读框架类...

标签: ios uiview uibutton


【解决方案1】:

注意确定如果这是问题但可能。

来自UIImageView 文档:

默认情况下,新的图像视图对象被配置为忽略用户事件。如果要在 UIImageView 的自定义子类中处理事件,则必须在初始化对象后将 userInteractionEnabled 属性的值显式更改为 YES。

【讨论】:

  • skinnyTOD 是对的。您应该将属性userInteractionEnabled 更改为YES,因为UIImageViews 默认为NO
【解决方案2】:

为将来的搜索者的利益而发布...

如果启用UIImageViewuserInteractionEnabled 属性不起作用,另一件要查看的事情是UIButton 的视图是否在其父视图的框架之外。

当对象的视图超出其父视图的框架时,它会出现在用户面前,但无法接收触摸事件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多