UIButton添加到UIImageView时的操作不起作用?

时间:2012-09-05 08:11:51

标签: iphone ios ipad

  

可能重复:
  Button action not working in iphone?

我有一个应用程序,其中代替导航栏视图我正在添加图像视图。在视图中就像这样做了加载方法。

curtainsView=[[UIImageView alloc]init];

curtainsView.image=[UIImage imageNamed:@"curtains.png"];
curtainsView.frame=CGRectMake(0,-44, 320, 60);
curtainsView.backgroundColor=[UIColor clearColor];

[self.view addSubview:curtainsView];

现在我想在该图像视图上添加一个按钮。我正在尝试使用此

来实现
UIImage *button2Image = [UIImage imageNamed:@"scroll_down.png"];
UIButton *scroll = [UIButton buttonWithType:UIButtonTypeCustom];
//scroll = [[UIButton alloc] init];
//self.scroll.tag=100;
[scroll setImage:button2Image forState:UIControlStateNormal];
scroll.frame = CGRectMake(270,-30, 40,40);
[scroll addTarget:self action:@selector(backpressed) forControlEvents:UIControlEventTouchUpInside]; 
//[scroll setUserInteractionEnabled:YES];
[self.view addSubview:scroll];

不工作。然后我也尝试了这个

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

btnDetail.frame = CGRectMake(260,-15,100,100);
[btnDetail addTarget:self action:@selector(backpressed) forControlEvents:UIControlEventAllTouchEvents];

[self.curtainsView addSubview:btnDetail];
[self.curtainsView bringSubviewToFront:btnDetail];
[self.curtainsView setUserInteractionEnabled:YES];

也不行。如果它在图像视图的一侧不起作用,但是当我尝试添加第二个代码时,框架CGRectMake(260,0,100,100)正在工作。但是我需要那个按钮才能进入图像视图。有人可以帮我吗?

4 个答案:

答案 0 :(得分:1)

您不应在imageViews上添加子视图。 而是将您的按钮添加到imageView上方的self.view。 并且不要在超视图边界之外添加按钮。

UIImage *button2Image = [UIImage imageNamed:@"scroll_down.png"];
UIButton *scroll = [UIButton buttonWithType:UIButtonTypeCustom];
[scroll setImage:button2Image forState:UIControlStateNormal];
scroll.frame = CGRectMake(270, 0, 40, 40);
[scroll addTarget:self action:@selector(backpressed) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:scroll];

答案 1 :(得分:0)

这将有效:

UIImageView *imgview=[[UIImageView alloc]initWithFrame:CGRectMake(10, 100, 300, 300)];
imgview.backgroundColor=[UIColor whiteColor];
imgview.userInteractionEnabled=YES;
[self.view addSubview:imgview];


UIButton *btn=[UIButton buttonWithType:UIButtonTypeCustom];
btn.Frame=CGRectMake(10, 10, 100, 20);
btn.backgroundColor=[UIColor blueColor];
[btn addTarget:self action:@selector(clickActonOfButtons) forControlEvents:UIControlEventTouchUpInside];
[imgview addSubview:btn];
btn=nil;
[imgview release];

注意:如果要在按钮上添加图像......在这种情况下 imgview.userInteractionEnabled=NO;

答案 2 :(得分:0)

将您的ImgView的userInteractionEnabled设为YES,默认为NO。

UIImageView中的触摸不会传递给UIButton。

curtainsView.userInteractionEnabled=YES;

还将UIButton的userInteractionEnabled设置为YES

btnDetail.userInteractionEnabled=YES;

在设置CGRectMake(260,-15,100,100)等框架时,还要检查btnDetail的界限是否超出范围界限;

当你设置CGRectMake(260,0,100,100)时,它的工作原理是因为btnDetail的绑定在可见区域内并且在超视图范围内

答案 3 :(得分:0)

您需要在不在图像视图上的视图上添加按钮。 将您的按钮添加到self.view而不是imageview。

    [self.view addSubview:btnDetail];
    [self.view bringSubviewToFront:btnDetail];

它会正常工作。