moonmonkey
moonmonkey

Reputation: 135

Possible to animate NSSwitch when changing state programatically?

I am controlling an NSSwitch state in a function. I declared trigger1ToggleOut outlet earlier, when I trigger the function the switch turns on, but it happens instantly, without the sliding animation. Is there a way to make it animate? (like you can do with progress indicators)

func turnSwitchOn()
    {
      trigger1ToggleOut.state = .on
    }

Any help would be great.

Upvotes: 2

Views: 241

Answers (2)

Sandeep Bhandari
Sandeep Bhandari

Reputation: 20379

Adding my comment as answer, Quoting from apple doc

The values off and on indicate that the switch is in the off or on position. The switch treats any value other than off as on. Setting this property through the animator() proxy animates the switch to the new value.

So you can change your turnSwitchOn method to use animator() proxy as shown below

    func turnSwitchOn() {
        trigger1ToggleOut.animator().state = .on
    }

Here is the O/P

enter image description here

Upvotes: 4

Imran0001
Imran0001

Reputation: 628

You can declare switch as -

var mySwitch = UISwitch()

Setting the switch on

mySwitch.setOn(true, animated: true)

For turning it off

mySwitch.setOn(false, animated: true)

This will animate while changing the state.

Upvotes: 0

Related Questions