UITapGestureRecognizer initWithTarget:action: method to take arguments?

↘锁芯ラ 提交于 2019-12-20 10:59:27

问题


I'm using UITapGestureRecognizer because I'm using a UIScrollView that acts as a container for my UILabels. Basically I'm trying to use an action method with arguments so I can e.g. send myLabel.tag value to the action method to know what action to take depending on what UILabel has has been triggered by a tap.

One way of doing it is having as many action methods as UILabels but that isn't very "pretty" codewise. What I would like to achieve is just having one action method with switch statements.

Is this possible or will I have to do it like this (sigh):

UITapGestureRecognizer *myLabel1Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel1Tap)];
[myLabel1Tap addGestureRecognizer:myLabel1Tap];

UITapGestureRecognizer *myLabel2Tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabel2Tap)];
[myLabel1Tap addGestureRecognizer:myLabel2Tap];

UITapGestureRecognizer *myLabelNTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelNTap)];
[myLabel1Tap addGestureRecognizer:myLabelNTap];

- (void)myLabel1Tap {
// Perform action
}

- (void)myLabel2Tap {
// Perform action
}

- (void)myLabelNTap {
// Perform action
}

回答1:


Add a single gesture recognizer to the view that is the superview of your various labels:

UITapGestureRecognizer *myLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myLabelTapHandler:)];
[myLabelParent addGestureRecognizer:myLabelTap];

Then when you handle the gesture, determine which label was tapped:

-(void)myLabelTapHandler:(UIGestureRecognizer *)gestureRecognizer {
    UIView *tappedView = [gestureRecognizer.view hitTest:[gestureRecognizer locationInView:gestureRecognizer.view] withEvent:nil];

    // do something with it
}



回答2:


You can use just one UITapGestureRecognizer and in your gesture handler (your myLaberXTap), which has the syntax:

 - (void)handleGesture:(UITapGestureRecognizer*)gestureRecognizer {
     ...
 } 

use gesture.view to know which view you are working on.



来源:https://stackoverflow.com/questions/6631023/uitapgesturerecognizer-initwithtargetaction-method-to-take-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!