Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to set a UISwitch programmatically

I want to set my UISwitch to on or off programmatically. How would I do that? I am an iOS newbie.

like image 261
Suchi Avatar asked Oct 17 '11 21:10

Suchi


People also ask

How do you set UISwitch state programmatically?

import UIKit class ViewController: UIViewController { override func viewDidLoad() { super. viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let switchDemo=UISwitch(frame:CGRect(x: 150, y: 150, width: 0, height: 0)) switchDemo. addTarget(self, action: #selector(self.

How do I use UISwitch Swift?

The UISwitch class declares a property and a method to control its on/off state. When a person manipulates the switch control (“flips” it), it triggers the valueChanged event. You can customize the appearance of the switch by changing the color used to tint the switch when it's on or off.


2 Answers

If you are using a UISwitch, then as seen in the developer API, the task setOn: animated: should do the trick.

- (void)setOn:(BOOL)on animated:(BOOL)animated 

So to set the switch ON in your program, you would use:

Objective-C

[switchName setOn:YES animated:YES]; 

Swift

switchName.setOn(true, animated: true) 
like image 110
Andrew_L Avatar answered Sep 21 '22 17:09

Andrew_L


UISwitches have a property called "on" that should be set.

Are you talking about an iOS app or a mobile web site?

like image 37
NWCoder Avatar answered Sep 22 '22 17:09

NWCoder