ios - 使用选择器为 UItapgestureRecognizer 传递额外参数

标签 ios swift selector

我有两个标签,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/

相关文章:

objective-c - 函数 'didFinishLaunchingWithOptions' 被不当调用

ios - 一段时间后如何显示 UIAlertView?

ios - Apple 示例代码中的错误代码?

objective-c - 我们可以从线程(NSThread)调用异步 NSURLRequest 吗?

objective-c - 我可以在 NS_SWIFT_NAME 中使用保留关键字吗?

javascript - 如何在 Cypress 中获取所有特定按钮并单击具有特定数据 ID 的每个按钮

javascript - 如何使用 jQuery 对象作为委托(delegate)方法的参数

swift - SKSpriteNode .run 不工作或不完全工作

arrays - Swift 的数组相等概念中的错误?

html - 当 CSS 选择器在 CSS 文件的一个部分中定义而不在另一个部分中定义时,CSS 选择器会影响 HTML 元素吗?