How do i keep UISwitch state when changing ViewControllers?
Xcode 8.3 • Swift 3.1
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var switchButton: UISwitch!
override func viewDidLoad() {
super.viewDidLoad()
switchButton.isOn = UserDefaults.standard.bool(forKey: "switchState")
}
@IBAction func saveSwitchPressed(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "switchState")
}
}
Pass UISwitch State from One View Controller to Another ViewController
Don't try to access another view controller's view hierarchy directly. You should treat another view controllers views (and a switch is a kind of view) as private.
Set an IBAction on your switch that points to the owning view controller. In that action save the sate of the switch to a property of your view controller.
You can then access the property from the other view controller.
Save UISwitch state in UserDefaults
This is not an answer to your original query, but an answer to another query in the comment. Question: How to set the default state of UISwitch as on, if application is launched for the first time?
Though ideally, it should be asked as another question, given it is incremental, the code is below:
import UIKit
class ViewController: UIViewController {
let userDefaults = UserDefaults.standard
var firstTimeAppLaunch: Bool {
get {
// Will return false when the key is not set.
return userDefaults.bool(forKey: "firstTimeAppLaunch")
}
set {}
}
@IBOutlet weak var mySwitch: UISwitch!
@IBAction func switchAction(_ sender: UISwitch) {
userDefaults.set(sender.isOn, forKey: "mySwitchValue")
}
override func viewDidLoad() {
super.viewDidLoad()
if !firstTimeAppLaunch {
// This will only be trigger first time the application is launched.
userDefaults.set(true, forKey: "firstTimeAppLaunch")
userDefaults.set(true, forKey: "mySwitchValue")
}
// Do any additional setup after loading the view, typically from a nib.
}
override func viewDidAppear(_ animated: Bool) {
mySwitch.isOn = userDefaults.bool(forKey: "mySwitchValue")
}
}
Note that you could do this within AppDelegate's function:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Could add the above code within this as well. Upto you.
return true
}
How to check the state of an UISwitch from another ViewController in SWIFT 3?
NOTE: THIS IS THE VERSION FOR SWIFT 3:
First of all, I've set the initial state
of the switch
to off. I have added a button, which leads us to the secondViewController and also checks the state of the switch. Here is my code(for the View Controller which contains the switch):
@IBOutlet weak var switch1: UISwitch!
let defaults = UserDefaults.standard
var switchON : Bool = false
@IBAction func checkState(_ sender: AnyObject) {
if switch1.isOn{
switchON = true
defaults.set(switchON, forKey: "switchON")
}
if switch1.isOn == false{
switchON = false
defaults.set(switchON, forKey: "switchON")
}
}
And for the secondView
:
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
if defaults.value(forKey: "switchON") != nil{
let switchON: Bool = defaults.value(forKey: "switchON") as! Bool
if switchON == true{
self.view.backgroundColor = UIColor.red()
}
else if switchON == false{
self.view.backgroundColor = UIColor.green()
}
}
}
Related Topics
Swiftui Modal Presentation Works Only Once from Navigationbaritems
Parse Multipart Response for Image Download in iOS
Playing Back Audio Using Avaudioplayer iOS 7
iOS Autolayout Multi-Line Uilabel
Arkit Hide Objects Behind Walls
Tracking Multiple (20+) Locations with iOS Geofencing
Why Page Push Animation Tabbar Moving Up in the iPhone X
How Does the Whatsapp Web Client Still Work with the Latest iOS Update (Sdk Version 13.0+)
Swift: Retrieving Text from a Uitextfield in a Custom Uitableviewcell and Putting It in an Array
How to Convert Date Like \/Date(1440156888750-0700)\/ to Something That Swift Can Handle
Why Is This Code Not Recognising the Nsstring as Being Equal
Error: Cuicatalog: Invalid Asset Name Supplied: (Null), or Invalid Scale Factor:2.000000
How to Add a Button to Uinavigationbar
Xcode - Symbol(S) Not Found for Architecture X86_64 (iOS Lib)