使用选择器为UItapgestureRecognizer传递额外参数 [英] Pass extra argument for UItapgestureRecognizer with selector

查看:114
本文介绍了使用选择器为UItapgestureRecognizer传递额外参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个标签,Label1和Label2。我想创建一个单独的函数,通过为两个标签创建UITTapRecognizer来打印出哪个标签被调用,该标签使用传递参数的选择器调用相同的函数。以下是漫长的做法,这很麻烦,但有效。如果我知道如何将参数(Int)传递给选择器,它将会更加清晰。

I have two labels, Label1 and Label2. I want to make a single function that prints out which label is tapped by creating UITTapRecognizer for both labels calling the same function with selector that passes an argument. Below is the long way of doing it which is messy but works. If I know how to pass an argument (Int) into the selector, it would be alot cleaner.

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")
}

有没有办法修改选择器方法如我可以做点什么ike

Is there a way to modify the selector method such that I can do something like

func doubleTapTopComment(label:Int) {
    if label == 1 {
        print("label \(label) double tapped")
}


推荐答案

简答:否

选择器由 UITapGestureRecognizer 调用,你对它传递了什么参数。

The selector is called by the UITapGestureRecognizer, and you have no influence on what parameters it passes.

但是,您可以做的是查询识别器的视图属性以获取相同的信息。

However, what you can do is query the recognizer's view property to get the same information.

func doubleTapComment(recognizer: UIGestureRecognizer) {
    if recognizer.view == label1 {
        ...
    }
    else if recognizer.view == label2 {
        ...
    }
}

这篇关于使用选择器为UItapgestureRecognizer传递额外参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆