【问题标题】:Passing arguments to #selector method in swift [duplicate]快速将参数传递给#selector方法[重复]
【发布时间】:2016-07-12 12:30:21
【问题描述】:

我想在单击图像时将多个参数传递给函数。 这是我的代码

var param1 = 120
var param2 = "hello"
var param3 =  "world"

let image: UIImage = UIImage(named: "imageName")!
 bgImage = UIImageView(image: image)

let singleTap = UITapGestureRecognizer(target: self, action:#selector(WelcomeViewController.tapDetected(_:secondParam:thirdParam:)))
singleTap.numberOfTapsRequired = 1
bgImage!.userInteractionEnabled = true
bgImage!.addGestureRecognizer(singleTap)

调用函数

func tapDetected(firstParam: Int, secondParam: String, thirdParam: String) {
print("Single Tap on imageview")
            print(firstParam)  //print 120
            print(secondParam) // print hello
            print(thirdParam) /print world
        }

如何传递参数以便获得正确的值?

【问题讨论】:

    标签: swift swift2 uitapgesturerecognizer


    【解决方案1】:

    你不能。来自文档:

    手势识别器有一个或多个与之关联的目标-动作对。
    ...
    调用的操作方法必须符合以下签名之一:

    - (void)handleGesture;
    - (void)handleGesture:(UIGestureRecognizer *)gestureRecognizer;
    

    您可以使用实例变量来传递参数。

    【讨论】:

    • 在我的特殊情况下如何使用实例变量?
    • 这实际上与 Shadow Of 的回答中建议的相同。
    • 好的,刚刚尝试了选项,子类 UIGestureRecognizer 并添加所需的属性。有效。类 MyTapGestureRecognizer:UITapGestureRecognizer { var 标题:字符串? } stackoverflow.com/questions/35635595/…
    • 其实instance variables的意思是不继承UITapGestureRecognizer,而是在使用识别器的目标类中创建属性。
    【解决方案2】:

    在 swift2 中,您不能在操作中传递参数。您可以只使用类属性:

    var param1 = 120
    var param2 = "hello"
    var param3 = "world"
    let image: UIImage = UIImage(named: "imageName")!
    var bgImage: UIImageView?
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        bgImage = UIImageView(image: image)
        let singleTap = UITapGestureRecognizer(target: self, action: #selector(WelcomeViewController.tapDetected))
        singleTap.numberOfTapsRequired = 1
        bgImage!.userInteractionEnabled = true
        bgImage!.addGestureRecognizer(singleTap)
    }
    

    调用函数

    func tapDetected() {
        print("Single Tap on imageview")
        print(param1) // print 120
        print(param2) // print hello
        print(param3) // print world
    } 
    

    【讨论】:

    • 在此 URL 中,他们提到了与 swift 2.2 stackoverflow.com/questions/36166248/… 中的多个参数相关的内容
    • @Vinod 您可以使用任意数量/名称的参数定义 Selector,但我们需要 UITapGestureRecognizer 的能力来支持它们,使用一些指定的参数调用选择器,而 UITapGestureRecognizer 没有这个能力
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多