Home > OS >  How to pass argument in button's addtarget function?
How to pass argument in button's addtarget function?

Time:09-28

I have a button that I wrote by code.

func someFunc(id: Int) {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
}

I need that when I click on the button it sends id (that is written in the above function) to my function.

So, i am writing @objc func

@objc func buttonAction(sender: UIButton) {

    passIdHere(id: Int) //here I need to write my id inspite of int
        
}

And adding this to my button.

button.addTarget(self, action: #selector(buttonAction(sender:)), for: .touchUpInside)

Can anyone help?

CodePudding user response:

You can´t do that as you plan to do. But UIButton has a .tag property of type Int. You can use that to pass the id on.

func someFunc(id: Int) {
    let button = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
    // add the tag to the button
    button.tag = id
}

and then:

@objc func buttonAction(sender: UIButton) {
    // read the id from the tag
    passIdHere(id: sender.tag ) //here I need to write my id inspite of int
    
}

Edit:

Regarding your comment on using a Dictionary as parameter:

This would need a bit more coding.

//Create a custom class that derives from UIButton
class MyButton: UIButton{
    //Create a variable to hold your array and initialize it
    var anyTag: [Int:String] = [:]
}

func someFunc(id: Int) {
    //Create a MyButton instead of a Button
    let button = MyButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
    // add the tag to the button
    button.anyTag = [1:"test"]
}

@objc func buttonAction(sender: UIButton) {
    // cast the sender to MyButton
    guard let button = sender as? MyButton else{
        return
    }
    
    // retrieve the dictionary
    let dictionary: [Int:String] = button.anyTag
    
}
  • Related