Attach parameter to button.addTarget action in Swi

2019-01-02 18:22发布

I am trying to pass an extra parameter to the buttonClicked action, but cannot work out what the syntax should be in Swift.

button.addTarget(self, action: "buttonClicked:", forControlEvents: UIControlEvents.TouchUpInside)

Any my buttonClicked method:

func buttonClicked(sender:UIButton)
{
    println("hello")
}

Anyone any ideas?

Thanks for your help.

10条回答
倾城一夜雪
2楼-- · 2019-01-02 18:27

In Swift 3 make a selector like that:

button.addTarget(self, action: #selector(ViewController.multipleParamSelector(_:secondParams:)), for: .touchUpInside)

And catch the event like that:

func multipleParamSelector(_ sender: AnyObject, secondParams: AnyObject) {

}
查看更多
大哥的爱人
3楼-- · 2019-01-02 18:28

I appreciate everyone saying use tags, but really you need to extend the UIButton class and simply add the object there..

Tags are a hopeless way round this. Extend the UIButton like this (in Swift 4)

import UIKit
class PassableUIButton: UIButton{
    var params: Dictionary<String, Any>
    override init(frame: CGRect) {
        self.params = [:]
        super.init(frame: frame)
    }

    required init?(coder aDecoder: NSCoder) {
        self.params = [:]
        super.init(coder: aDecoder)
    }
}

then your call may be call (NOTE THE colon ":" in Selector(("webButtonTouched:")))

let webButton = PassableUIButton(frame: CGRect(x:310, y:40, width:40, height:40))
webButton.setTitle("Visit",for: .normal)
webButton.addTarget(self, action: #selector(YourViewController.webButtonTouched(_:)), for:.touchUpInside)
webButton.params["myvalue"] = "bob"

then finally catch it all here

@IBAction func webButtonTouched(_ sender: PassableUIButton) {
    print(sender.params["myvalue"] ?? "")
}

You do this one time and use it throughout your project (you can even make the child class have a generic "object" and put whatever you like into the button!). Or use the example above to put an inexhaustible number of key/string params into the button.. Really useful for including things like urls, confirm message methodology etc

As an aside, it's important that the SO community realise this there is an entire generation of bad practice being cut'n'paste round the internet by an alarming number of programmers who don't understand/haven't been taught/missed the point of the concept of object extensions

查看更多
临风纵饮
4楼-- · 2019-01-02 18:37

For Swift 3.0 you can use following

button.addTarget(self, action: #selector(YourViewController.YourMethodName(_:)), for:.touchUpInside)

func YourMethodName(_ sender : UIButton) {
    print(sender.tag)

}
查看更多
荒废的爱情
5楼-- · 2019-01-02 18:39

For Swift 2.X and above

button.addTarget(self,action:#selector(YourControllerName.buttonClicked(_:)),
                         forControlEvents:.TouchUpInside)
查看更多
春风洒进眼中
6楼-- · 2019-01-02 18:44

If you want to send additional parameters to the buttonClicked method, for example an indexPath or urlString, you can subclass the UIButton:

class subclassedUIButton: UIButton {
    var indexPath: Int?
    var urlString: String?
}

Make sure to change the button's class in the identity inspector to subclassedUIButton. You can access the parameters inside the buttonClicked method using sender.indexPath or sender.urlString.

Note: If your button is inside a cell you can set the value of these additional parameters in the cellForRowAtIndexPath method (where the button is created).

查看更多
笑指拈花
7楼-- · 2019-01-02 18:46

If you have a loop of buttons like me you can try something like this

var buttonTags:[Int:String]? // can be [Int:Any]
let myArray = [0:"a",1:"b"]
for (index,value) in myArray {

     let button = // Create a button

     buttonTags?[index] = myArray[index]
     button.tag = index
     button.addTarget(self, action: #selector(buttonAction(_:)), for: .touchDown)

}
@objc func buttonAction(_ sender:UIButton) {

    let myString = buttonTags[sender.tag]

}
查看更多
登录 后发表回答