简体   繁体   中英

How to add a function with parameter in addTarget of UIButton in swift 5?

I am a newbie in swift. I have a problem with UIButton. I have a function with parameters which I want to call by the addTarget method of a UIButton . When I am going to add this function on addTarget it gives me the following error- Type of expression is ambiguous without more context

I am also sharing my code part for reference. Please help me with this

//button initialization
let MainSkipButton = UIButton(type: .custom)
MainSkipButton.frame = CGRect(x: 50 , y: 48, width: 47.0, height: 24.0)
MainSkipButton.backgroundColor = .blue
MainSkipButton.layer.cornerRadius = 10
MainSkipButton.layer.borderWidth = 1
MainSkipButton.layer.borderColor = UIColor.white.cgColor
MainSkipButton.setTitle(NSLocalizedString("Skip", comment: "Button"), for: .normal)
MainSkipButton.setTitleColor(.white, for: .normal)
MainSkipButton.addTarget(self, action: #selector(buttonActionSkip(sender: UIButton, name: String)), for: .touchUpInside)
self.view.addSubview(MainSkipButton)

//function initialization
 @objc func buttonActionSkip(sender: UIButton, name: String) {
        print("Receive parameter string is\(name)")
        sender.isHidden = true
    }

I don't believe it is possible to pass custom parameters to a #selector , as stated here ,

Action methods must have a conventional signature. The UIKit framework permits some variation of signature, but both platforms accept action methods with a signature similar to the following:

meaning you method can at least have one of the following signatures:

@objc func buttonActionSkip(sender: UIButton)
@objc func buttonActionSkip(sender: UIButton, for event: UIEvent)

You can however, change the sender type. A possible solution for your problem could be extending the UIButton class adding a name property:

class MyMainSkipButton: UIButton {
    var name: String = ""
}

Then on your code:

//button initialization
let MainSkipButton = MyMainSkipButton(type: .custom)
MainSkipButton.frame = CGRect(x: 50 , y: 48, width: 47.0, height: 24.0)
MainSkipButton.backgroundColor = .blue
MainSkipButton.layer.cornerRadius = 10
MainSkipButton.layer.borderWidth = 1
MainSkipButton.layer.borderColor = UIColor.white.cgColor
MainSkipButton.setTitle(NSLocalizedString("Skip", comment: "Button"), for: .normal)
MainSkipButton.setTitleColor(.white, for: .normal)
MainSkipButton.name = "what ever the name is"
MainSkipButton.addTarget(self, action: #selector(buttonActionSkip(sender:)), for: .touchUpInside)
self.view.addSubview(MainSkipButton)


//function initialization
 @objc func buttonActionSkip(sender: MyMainSkipButton) {
    print("Receive parameter string is\(sender.name)")
    sender.isHidden = true
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM