Search code examples
iosswiftselector

Can I add attribute value to selector in swift?


I have been reading about selectors all over and would now like to know if there is a way how I could send a value for function attribute over selector.

I have a method:

@objc func acceptBiometrics(newValue: Int){
}

And a selector:

#selector(acceptBiometrics(newValue:))

So is there a way I could send lets say 1 as new value, so that I could have two selector that call the same function, just with different value?

EDIT 1: I am then sending this selector to some view controller to create my own alert view controller with a button. So the selector gets called in a totally different view controller. Is it the only way to do this then to also send that vc also the value I want to send with selector? There isn't a way I could do something like #selector(self.acceptBiometrics(newValue:1))


Solution

  • You don't.

    You can use the button.tag and set 1 (or any other Int value) to it.

    let button = UIButton()
    button.tag = 1
    button.addTarget(self, action: #selector(acceptBiometrics(_ :)), for: .touchUpInside)
    

    Then on your handler:

    @objc func acceptBiometrics(_ sender : UIButton) {
        print(sender.tag)
    }
    

    Notes:

    A tag attribute is an Int variable, so if you want any other Type you should create a custom UIButton with just a new variable.

    The tag default value is 0, which means if 0 is a possible value in your logic, you should also do the custom component approach.

    As @matt pointed out, "a selector is the name of a method, not a call to a method".

    As @Sulthan pointed out, "Subclassing is the real solution".

    A subclass would look like this:

    class ButtonWithValue : UIButton {
        var value : Int? // note that this could be any Type.
    }
    

    Then your instantiate it, and update your sender parameter type to ButtonWithValue. Inside the handler you check for sender.value