11

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

一种方法是拥有与UILabels 一样多的操作方法,但这在代码方面并不是很“漂亮”。我想要实现的只是使用一种带有 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
}
4

2 回答 2

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
}
于 2011-07-09T01:06:29.763 回答
5

您可以UITapGestureRecognizer在手势处理程序 (your myLaberXTap) 中仅使用一个 and ,其语法如下:

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

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

于 2011-07-08T22:05:20.657 回答