开发者

How to add gesture recognizers to multiple buttons?

开发者 https://www.devze.com 2023-04-12 13:20 出处:网络
Hi, I am trying to add gesture recognizers to \'UIButton\'. When I do it like this: UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSing

Hi, I am trying to add gesture recognizers to 'UIButton'. When I do it like this:

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

It works properly, but when I tried to add this gesture to multiple buttons it did not work:

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:doub开发者_开发技巧leTap];
[singleTap release];

So how can I add the same gesture to multiple buttons in the same way I have added the 'longPress' and 'doubleTap'?


I'd suggest the following:

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

If you save the set as a variable, you can do other stuff for all buttons as well, such as releasing them all and changing all their backgroundColors, without calling them all individually.

You will probably need to make seperate doubletaprecognizers for each button as well.


You can add one gesture recognizer to one view alone. If you add it to more than one views, the last added view will be added with the recognizer.

Create different instances of gesture recognizers and add them to individual views.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号