Passing arguments to selector in Swift

后端 未结 6 669
闹比i
闹比i 2020-11-27 03:14

I\'m programmatically adding a UITapGestureRecognizer to one of my views:

let gesture = UITapGestureRecognizer(target: self, action: #selector(self.handleTap         


        
6条回答
  •  春和景丽
    2020-11-27 03:33

    Step 1: create the custom object of the sender.

    step 2: add properties you want to change in that a custom object of the sender

    step 3: typecast the sender in receiving function to a custom object and access those properties

    For eg: on click of the button if you want to send the string or any custom object then

    step 1: create

    class CustomButton : UIButton {
    
        var name : String = ""
        var customObject : Any? = nil
        var customObject2 : Any? = nil
    
        convenience init(name: String, object: Any) {
            self.init()
            self.name = name
            self.customObject = object
        }
    }
    

    step 2-a: set the custom class in the storyboard as well

    step 2-b: Create IBOutlet of that button with a custom class as follows

    @IBOutlet weak var btnFullRemote: CustomButton!
    

    step 3: add properties you want to change in that a custom object of the sender

    btnFullRemote.name = "Nik"
    btnFullRemote.customObject = customObject
    btnFullRemote.customObject2 = customObject2
    btnFullRemote.addTarget(self, action: #selector(self.btnFullRemote(_:)), for: .touchUpInside)
    

    step 4: typecast the sender in receiving function to a custom object and access those properties

    @objc public func btnFullRemote(_ sender: Any) {
    
    var name : String = (sender as! CustomButton).name as? String
    
    var customObject : customObject = (sender as! CustomButton).customObject as? customObject
    
    var customObject2 : customObject2 = (sender as! CustomButton).customObject2 as? customObject2
    
    }
    

提交回复
热议问题