UITapGestureRecognizer initWithTarget:action:接受参数的方法? [英] UITapGestureRecognizer initWithTarget:action: method to take arguments?
问题描述
我正在使用UITapGestureRecognizer
,因为我正在使用UIScrollView
作为我的UILabel
的容器.基本上我正在尝试使用带有参数的操作方法,以便例如将myLabel.tag
值发送到action方法,以根据要通过轻击触发的UILabel知道要执行什么操作.
I'm using UITapGestureRecognizer
because I'm using a UIScrollView
that acts as a container for my UILabel
s. 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.
一种实现方法是拥有与UILabel
一样多的动作方法,但这并不是十分漂亮"的代码方式.我想要实现的只是使用带switch语句的一种操作方法.
One way of doing it is having as many action methods as UILabel
s 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
}
推荐答案
向视图添加一个手势识别器,该识别器是您各种标签的超级视图:
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
}
这篇关于UITapGestureRecognizer initWithTarget:action:接受参数的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!