gpt4 book ai didi

ios - 运行指定的 ViewController

转载 作者:行者123 更新时间:2023-11-28 15:20:40 25 4
gpt4 key购买 nike

我有一个代码,这样在运行时,如果开关打开,就会显示指定 VC

但是没有任何反应,并且 switch 在重新启动后不保存它的值。

求助

SettingsVC.swift

@IBAction func switchChanged(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "isSwitchOn")
}

AppDelegate.swift

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isSwitchOn = UserDefaults.standard.bool(forKey: "isSwitchOn")
if isSwitchOn {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let VC2 = storyboard.instantiateViewController(withIdentifier: "ViewController")
self.window!.rootViewController = VC2;
}
// Override point for customization after application launch.
return true
}

编辑:

override func viewDidLoad() {
super.viewDidLoad()
Set.isOn = UserDefaults.standard.bool(forKey: "isSwitchOn")

// Do any additional setup after loading the view.
}

最佳答案

我注意到这里有两件事:

AppDelegate.swift

无论何时以编程方式调整窗口的 Root View Controller ,都需要调用 window?.makeKeyAndVisible 来显示新屏幕。

用户默认值

目前,您的代码不保证在重启之间保存用户默认值。 UserDefaults 会选择自己的时间将数据保存在磁盘上,如果您在此之前退出您的应用程序,它就不会及时保存。

我相信在模拟器上,如果您停止通过 Xcode 运行模拟器,这种情况总会发生。由于这是相当重要的行为,您可能需要调用 UserDefaults.standard.synchronize 来强制保存。

请注意,此调用通常会在特定时间间隔内自动为您完成;你明确地这样做是因为你不能错过它。

关于ios - 运行指定的 ViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46059250/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com