UITapGestureRecognizer initWithTarget:action:获取参数的方法?

时间:2011-07-08 22:02:39

标签: ios objective-c uiscrollview uilabel uitapgesturerecognizer

我正在使用UITapGestureRecognizer,因为我正在使用UIScrollView作为UILabel的容器。基本上我试图使用带参数的动作方法,所以我可以例如将myLabel.tag值发送到操作方法,以了解要采取的操作,具体取决于点击触发UILabel的操作。

这样做的一种方法是使用与UILabel一样多的动作方法,但这不是非常“漂亮”的代码。我想要实现的只是有一个带有switch语句的动作方法。

这是可能的还是我必须这样做(叹气):

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
}

2 个答案:

答案 0 :(得分:18)

将单个手势识别器添加到视图中,该视图是各种标签的超级视图:

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

然后,当您处理手势时,确定点击了哪个标签:

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

    // do something with it
}

答案 1 :(得分:5)

您只能使用一个UITapGestureRecognizer和您的手势处理程序(myLaberXTap),其语法为:

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

使用gesture.view了解您正在处理的视图。