UITapGestureRecognizer initWithTarget:action: 接受参数的方法?
我使用 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
}
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.
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
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将单个手势识别器添加到作为各种标签的超级视图的视图中:
然后,当您处理手势时,确定点击了哪个标签:
Add a single gesture recognizer to the view that is the superview of your various labels:
Then when you handle the gesture, determine which label was tapped:
您可以在手势处理程序(您的
myLaberXTap
)中仅使用一个UITapGestureRecognizer
,其语法为:使用
gesture.view
来了解哪个视图你正在努力。You can use just one
UITapGestureRecognizer
and in your gesture handler (yourmyLaberXTap
), which has the syntax:use
gesture.view
to know which view you are working on.