如何将手势识别器添加到多个按钮?

时间:2011-10-13 09:24:57

标签: iphone objective-c xcode cocoa-touch uitouch

嗨,我正在尝试为'UIButton'添加手势识别器。当我这样做时:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.LeftBottomSpaceBtn addGestureRecognizer:singleTap];
[singleTap requireGestureRecognizerToFail:doubleTap];
[singleTap release];

它工作正常,但当我尝试将此手势添加到多个按钮时,它无法正常工作:

UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
[self.LeftBottomSpaceBtn addGestureRecognizer:singleTap];
[self.LeftUpSpaceBtn addGestureRecognizer:singleTap];
[self.RightBUpSpaceBtn addGestureRecognizer:singleTap];
[self.LeftReturnBtn addGestureRecognizer:singleTap];
[self.RightReturnBtn addGestureRecognizer:singleTap];
[self.DeleteBtn addGestureRecognizer:singleTap];
[self.CapsBtn addGestureRecognizer:singleTap];
[singleTap requireGestureRecognizerToFail:doubleTap];
[singleTap release];

那么如何以与添加'longPress'和'doubleTap'相同的方式将相同的手势添加到多个按钮?

2 个答案:

答案 0 :(得分:8)

我建议如下:

NSMutableSet *buttons = [[NSMutableSet alloc] init];

[buttons addObject: self.LeftBottomSpaceBtn];
[buttons addObject: self.LeftUpSpaceBtn];
[buttons addObject: self.RightBUpSpaceBtn];
[buttons addObject: self.LeftReturnBtn];
[buttons addObject: self.RightReturnBtn];
[buttons addObject: self.DeleteBtn];
[buttons addObject: self.CapsBtn];

for(UIButton *button in buttons)
{
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [button addGestureRecognizer:singleTap];
    [singleTap requireGestureRecognizerToFail:doubleTap];
    [singleTap release];
}

如果将该集保存为变量,您也可以为所有按钮执行其他操作,例如全部释放它们并更改所有backgroundColors,而无需单独调用它们。

您可能还需要为每个按钮制作单独的双重识别。

答案 1 :(得分:5)

您可以单独向一个视图添加一个手势识别器。如果将其添加到多个视图中,则最后添加的视图将与识别器一起添加。

创建手势识别器的不同实例并将其添加到各个视图中。