我有两个标签,Label1 和 Label2。我想制作一个函数,通过为两个标签创建 UITTapRecognizer 并使用传递参数的选择器调用相同的函数来打印出哪个标签被点击。下面是实现它的漫长方法,它很困惑但有效。如果我知道如何将参数 (Int) 传递给选择器,它会更清晰。
let topCommentLbl1Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment1))
topCommentLbl1Tap.numberOfTapsRequired = 2
topCommentLbl1.userInteractionEnabled = true
topCommentLbl1.addGestureRecognizer(topCommentLbl1Tap)
let topCommentLbl2Tap = UITapGestureRecognizer(target: self, action: #selector(DiscoverCell().doubleTapTopComment2))
topCommentLbl2Tap.numberOfTapsRequired = 2
topCommentLbl2.userInteractionEnabled = true
topCommentLbl2.addGestureRecognizer(topCommentLbl2Tap)
func doubleTapTopComment1() {
print("Double Tapped Top Comment 1")
}
func doubleTapTopComment2() {
print("Double Tapped Top Comment 2")
}
有没有办法修改选择器方法,这样我就可以做类似的事情
func doubleTapTopComment(label:Int) {
if label == 1 {
print("label \(label) double tapped")
}
最佳答案
简答:否
选择器由 UITapGestureRecognizer
调用,您对其传递的参数没有影响。
但是,您可以查询识别器的 view
属性以获得相同的信息。
func doubleTapComment(recognizer: UIGestureRecognizer) {
if recognizer.view == label1 {
...
}
else if recognizer.view == label2 {
...
}
}
关于ios - 使用选择器为 UItapgestureRecognizer 传递额外参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38299162/