Reputation: 57
using UIswitch to set value my variable is static because im using them in diffrent swift file so when I run program and click registration button it prints nil even tho its on (button stays the way it was left when closing app) I have to toggle it and then click registration button for it to print optional(true) what can i do so user dont have to togggle everytime they open app or when it shows on when app opened but value is nil also I just want it to print true/false (how do i unwrap)
class FirstViewController: UIViewController, UITextFieldDelegate {
static var FirstColor: Bool!
@IBAction func home(_ sender: RoundButton) {
}
@IBAction func Registration(_ sender: RoundButton) {
print(FirstViewController.FirstColor)
}
@IBAction func ColorSwitch(_ sender: UISwitch) {
if sender.isOn{
FirstViewController.FirstColor = true
}else{FirstViewController.FirstColor = false }
}
}
Upvotes: 0
Views: 240
Reputation: 15748
If you want to persist the switch status you need to store it in UserDefaults. Don't add a static property in FirstViewController. Create a separate class like this with a computed property
class Color {
static var firstColor: Bool {
get { return UserDefaults.standard.bool(forKey: "firstColor") }
set { UserDefaults.standard.set(newValue, forKey: "firstColor") }
}
}
In FirstViewController's viewDidLoad get last status and update
override func viewDidLoad() {
super.viewDidLoad()
mySwitch.isOn = Color.firstColor
}
In Switch's action change it
@IBAction func ColorSwitch(_ sender: UISwitch) {
sender.isOn = !sender.isOn
Color.firstColor = sender.isOn
}
Upvotes: 1
Reputation: 2639
You could try to use the value of the isOn property directly. Does this help? Also I suggest that you use better names for your handlers.
class FirstViewController: UIViewController, UITextFieldDelegate
{
static var FirstColor: Bool!
@IBAction func registrationTapped(_ sender: RoundButton)
{
print(FirstViewController.FirstColor)
}
@IBAction func colorChanged(_ sender: UISwitch)
{
FirstViewController.FirstColor = sender.isOn
}
}
Upvotes: 0