winter4w winter4w - 4 years ago 150
Swift Question

Disable Button from another view controller with a switch with swift

Ok so I am trying to make it when the user flips the cheat mode switch it will disable the answerButton. I did try to set the button to disable near the bottom however it does not appear to do anything. I added the print("") to see if it would print in the console however nothing was printed. I a unsure what is wrong here.

I have pasted my code below.

import Foundation
import UIKit

class SettingsController: UITableViewController {

@IBOutlet weak var cheatSwitch: UISwitch!

override func viewDidLoad() {

cheatSwitch.isOn = UserDefaults.standard.bool(forKey: "switchState")

override func didReceiveMemoryWarning() {
// Dispose of any resources that can be recreated.

@IBAction func saveSettings(_ sender: UISwitch) {
UserDefaults.standard.set(cheatSwitch.isOn, forKey: "switchState")

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let mainView : ViewController = segue.destination as! ViewController

if cheatSwitch.isOn == true {
print("turn off button")
mainView.btnAnswer.isEnabled = false;


else {
print("turn on button")
mainView.btnAnswer.isEnabled = true;



Answer Source

You are saving the value UISwitch's state in UserDefaults so you can use its value in ViewController's method viewDidApper.

override func viewDidAppear(_ animated: Bool) {
    self.btnAnswer.isEnabled = !UserDefaults.standard.bool(forKey: "switchState")

Note: There is no need to add prepareForSegue in your SettingsController because it will never called when you press back button of NavigationController so consider to remove it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download