Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift UISwitch Selector inline

Tags:

swift

uiswitch

I know I am supposed to add target like this:

mySwitch.addTarget(self, action: Selector("selector"), for: UIControlEvents.valueChanged)

But I don't want a separate function for selector so I want to do something like this:

mySwitch.addTarget(self, action: Selector {
    if mySwitch.on {
        label.text = "Yes, Please! - For:"
        ........
    }
}, for: UIControlEvents.valueChanged)

which is not liked by swift, how can I do this?

like image 651
Kashif Avatar asked Jul 26 '26 16:07

Kashif


1 Answers

Unfortunately, you can't do it directly. Remember, you're dealing with the Cocoa framework. It's old and old-fashioned and written in Objective-C. And it was written long before Objective-C had blocks, and long before Swift existed. It has no notion of a UIControl's action function being described as a function (or an anonymous function body, as you're doing it); it has to be a selector, that is, in effect, the mere name of a method in the target.

You could perhaps write an extension to UIControl, or at least a UISwitch subclass, that implements this kind of thing, or there may be third-party frameworks that help you; but as things stand, your idea, though natural enough for someone accustomed to Swift, is doomed to failure.

like image 174
matt Avatar answered Jul 28 '26 11:07

matt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!