将UIButton添加到UIImageView时无法单击UIButton

时间:2010-08-20 08:19:13

标签: iphone uiimageview uibutton

伙计们,我想在添加到UIImageVIew之后点击我的uiButton,但它不起作用。 这是我的代码:

UIButton *btnDetail = [[UIButton buttonWithType:UIButtonTypeDetailDisclosure]retain];

btnDetail.frame = CGRectMake(0,0,100,100);
[btnDetail addTarget:self action:@selector(buttonClicked) forControlEvents:UIControlEventAllTouchEvents];

[self.imageView addSubview:btnDetail];

当我将它添加到UIImageVIew时,按钮无法单击,但如果我不将其添加到UIImageView,它可以正常工作。 请有人帮助我

4 个答案:

答案 0 :(得分:50)

注意:默认情况下,UserInteraction的{​​{1}}属性设置为。这是我们大多数人犯错误的地方。 因此,在向UIImageView添加任何控件时检查的主要方法是将其UIImageView属性设置为 YES

UserInteractionEnabled

所以修改你的代码如下:

[self.imageView setUserInteractionEnabled:YES];

HAppy Coding ...

答案 1 :(得分:5)

UIImageView默认情况下userInteractionProperty设置为NO,因此它不会处理触摸,也不会将它们传播到其子视图。尝试将其设置为YES:

self.imageView.userInteractionEnabled = YES;

答案 2 :(得分:3)

嘿,我使用过这段代码。它的工作正常

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
button.frame = CGRectMake(80.0, 210.0, 100.0, 20.0);
[button addTarget:self action:@selector(show) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"ShowView" forState:UIControlStateNormal];

[image2 addSubview:button];
[image2 bringSubviewToFront:button];
[image2 setUserInteractionEnabled:YES];

答案 3 :(得分:0)

如果某人在UIImageView中与UIButton存在交互问题,请执行后续步骤。

1创建UIImageView的属性:

@property (nonatomic, strong) UIImageView *buttonImageView;

2比合成它:

@synthesize buttonImageView = _buttonImageView;

3创建实施方法:

- (UIImageView *) buttonImageView {

    _buttonImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)];
    [_buttonImageView setBackgroundColor:[UIColor whiteColor]];
    [_buttonImageView setUserInteractionEnabled:YES];

    UIButton *addButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [addButton setTitle:@"add button" forState:UIControlStateNormal];
    addButton.frame = CGRectMake(0, 0, 160, 50);
    [addButton setUserInteractionEnabled:YES];
    [addButton setEnabled:YES];
    [addButton setAlpha:1];
    [addButton addTarget:self action:@selector(addNewImage) forControlEvents:UIControlEventTouchUpInside];

    return _buttonImageView;
}

4例如,在viewDidLoad方法中,将子视图添加到视图中:

[self.view addSubview:self.buttonImageView];