如何传递多个参数addTarget?

时间:2021-08-07 16:41:38

I need to pass two parameters. How can i pass by addTarget action. If it possible what changes i need to perform?

我需要传递两个参数。我如何通过addTarget操作传递。如果可能需要执行哪些更改?

This is my current code.

这是我目前的代码。

button.tag = numbers[index];
button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents:UIControlEvents.TouchUpInside)

func buttonClicked(sender: UIButton){
     print(sender.tag)
}

1 个解决方案

#1


1  

If you want more then one perimeter pass then you can use a objc_setAssociatedObject.
Any thing will be pass like Dictionary,Array,String,Int.

如果你想要超过一个周长传递,那么你可以使用objc_setAssociatedObject。任何东西都会像Dictionary,Array,String,Int一样传递。

import ObjectiveC

extension UIButton {
private struct AssociatedKeys {
    static var WithValue = "KeyValue"
}

@IBInspectable var withValue: String? {
    get {
        return objc_getAssociatedObject(self, &AssociatedKeys.WithValue) as? String
    }
    set {
        if let newValue = newValue {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.WithValue,
                newValue as NSString?,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
            )
        }
    }
}
}

You need to use above extension:-

您需要使用以上扩展名: -

import ObjectiveC

button.tag = numbers[index];
    button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents:UIControlEvents.TouchUpInside)

    //set velue
   button.withVelue = "1,2,3,4"

func buttonClicked(sender: UIButton){

     print(sender.withVelue)
}

#1


1  

If you want more then one perimeter pass then you can use a objc_setAssociatedObject.
Any thing will be pass like Dictionary,Array,String,Int.

如果你想要超过一个周长传递,那么你可以使用objc_setAssociatedObject。任何东西都会像Dictionary,Array,String,Int一样传递。

import ObjectiveC

extension UIButton {
private struct AssociatedKeys {
    static var WithValue = "KeyValue"
}

@IBInspectable var withValue: String? {
    get {
        return objc_getAssociatedObject(self, &AssociatedKeys.WithValue) as? String
    }
    set {
        if let newValue = newValue {
            objc_setAssociatedObject(
                self,
                &AssociatedKeys.WithValue,
                newValue as NSString?,
                objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN
            )
        }
    }
}
}

You need to use above extension:-

您需要使用以上扩展名: -

import ObjectiveC

button.tag = numbers[index];
    button.addTarget(self, action: #selector(ViewController.buttonClicked(_:)), forControlEvents:UIControlEvents.TouchUpInside)

    //set velue
   button.withVelue = "1,2,3,4"

func buttonClicked(sender: UIButton){

     print(sender.withVelue)
}