You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中UISwitch重启App后无法保留状态的解决方法

UISwitch重启后状态不保留的解决方法

问题根源

你的AppDelegate中,每次App启动都会执行UserDefaults.standard.set(true, forKey: "switchState"),这行代码会强制覆盖之前保存在UserDefaults里的开关状态,导致重启后开关永远处于开启状态。

解决步骤

  1. 移除AppDelegate的强制设置代码
    删除didFinishLaunchingWithOptions方法中设置switchState的代码,修改后代码如下:

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // 移除强制设置switchState的代码
        return true
    }
    
  2. (可选)设置默认初始状态
    如果需要首次启动时开关默认处于开启状态,修改ViewController中读取状态的逻辑,确保无历史记录时使用默认值:

    override func viewDidLoad() {
        super.viewDidLoad()
        modeSwitchStyleB.addTarget(self, action: #selector(switchBToggle(_:)), for: .valueChanged)
        // 无保存记录时默认设为开启
        let state = UserDefaults.standard.object(forKey: "switchState") as? Bool ?? true
        modeSwitchStyleB.setOn(state, animated: true)
    }
    

逻辑说明

修改后,App启动时会优先读取UserDefaults中保存的历史状态;如果是首次启动(无保存记录),则使用你设置的默认值。开关切换时的保存逻辑保持不变,重启后就能正确保留最后一次的状态了。

内容的提问来源于stack exchange,提问作者lin lin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 05:40:31