ios - 如何从 SWIFT 3 中的另一个 ViewController 检查 UISwitch 的状态?

标签 ios xcode uiswitch swift3

我想从另一个 View Controller 检查 UISwitch 的状态。如果 switchon,那么我希望 ViewbackgroundColor 是红色的,否则它应该是绿色的。我尝试使用 UserDefaults,但我不知道从什么开始。任何帮助将不胜感激!

最佳答案

注意:这是 SWIFT 3 的版本:

首先,我将开关初始状态设置为关闭。我添加了一个按钮,它将我们带到 secondViewController 并检查开关的状态。这是我的代码(用于包含开关的 View Controller ):

    @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")
        }
    
    }

对于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()
            }
        }
    }
    

Main.storyboard

关于ios - 如何从 SWIFT 3 中的另一个 ViewController 检查 UISwitch 的状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38811706/

相关文章:

ios - React Native OneSignal 访问启动应用程序启动的推送通知

iphone - iOS Safari 页面上方奇怪的灰色空间

ios - 平衡ios电池生命周期和定位精度

ios - UICollectionView 单元格的水平重新排序

ios - CABasicAnimation 在 UIStackView 中不可靠?

objective-c - 使用 FMDB 保存到数据库在解释 NSInteger 时崩溃

xcode - 将plist读入nsmutabledictionary,更新字典然后再次保存

java - Java 中是否有标准的 GUI 切换开关?

ios - 如何为 Storyboard初始化的开关按钮设置默认 boolean 值

ios - UICollectionView 中 UISwitch 的错误数据表示