捕捉动态按钮点击ios

时间:2012-02-10 14:06:54

标签: objective-c ios ios5

我在UIImageView中以编程方式创建了按钮。此视图也是以编程方式创建的。当点击此视图中的图像时,按钮被创建,现在我想要在点击此按钮时捕获但是我无法在这里找到我的相关代码:

- (void)imageTapped:(UIGestureRecognizer *)sender{ 
    MyImageView *myView = (MyImageView *)sender.view;
    NSLog(@"Image tapped is => %@", myView.currentImageName); 

    //add button to view
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button addTarget:self 
               action:@selector(pressedPlay:)
     forControlEvents:UIControlEventTouchDown];

    //button image
    UIImage *backgroundImage = [UIImage imageNamed:[NSString stringWithFormat:@"playbutton.png"]];

    button.frame = CGRectMake(85.0, 175.0, backgroundImage.size.width, backgroundImage.size.height);

    myView.userInteractionEnabled = YES;
    button.userInteractionEnabled = YES;

    [button setImage:backgroundImage forState:(UIControlStateNormal)];
    [myView addSubview:button];
}

现在这段代码应该处理点击,但由于某种原因它不会:

- (void)pressedPlay:(UIGestureRecognizer *)sender{ 
    //MyImageView *senderView = (MyImageView *) sender.view;
    NSLog(@"%@", @"I Presed button");    
}

为什么这不起作用?

4 个答案:

答案 0 :(得分:1)

您的代码建议您使用UIGestureRecognizer(最有可能是UITapGestureRecognizer)来检测初始点按。问题是UIGestureRecognizer贪婪并阻止UIButton接触。

您需要进行一些调整以在初始检测后禁用手势识别器,然后在点击播放后重新启用它。

UIGestureRecognizer拥有属性

@property(nonatomic, getter=isEnabled) BOOL enabled

或者您可以选择实施UIGestureRecognizerDelegate并提供

的实施
gestureRecognizer:shouldReceiveTouch:

一个非常简单的尝试可能看起来像:

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch;
{
    return ![touch.view isKindOfClass:[UIButton class]];
}

并且不要忘记在手势识别器上设置委托

myGesture.delegate = self;

答案 1 :(得分:0)

设置按钮框架:

button.frame = CGRectMake(85.0, 175.0, backgroundImage.size.width, backgroundImage.size.height);

为:

button.frame = CGRectMake(0,0, backgroundImage.size.width, backgroundImage.size.height);

看起来你在imageview的框架外面设置了按钮框,因此按钮实际上没有进行任何交互。

答案 2 :(得分:0)

Button框架很可能将按钮设置在UIImageView的边界之外,框架总是相对于超视图坐标,在这种情况下是UIImageView。

答案 3 :(得分:0)

[button setExclusiveTouch:YES];