运行指定的ViewController
Running the specified ViewController
我有一个代码,当 运行 时,指定 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
每当您以编程方式调整 window 的根视图控制器时,您需要调用 window?.makeKeyAndVisible
来显示新屏幕。
用户默认值
目前,您的代码不保证在重新启动之间保存用户默认设置。 UserDefaults
会选择自己的时间将数据保存在磁盘上,如果您在此之前退出您的应用程序,它不会及时保存。
我相信在模拟器上,如果您通过 Xcode 停止 运行 模拟器,总是会发生这种情况。由于这是相当重要的行为,您可能需要调用 UserDefaults.standard.synchronize
来强制保存。
请注意,此呼叫通常会在特定时间间隔自动为您完成;你明确地这样做是因为你不能错过它。
我有一个代码,当 运行 时,指定 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
每当您以编程方式调整 window 的根视图控制器时,您需要调用 window?.makeKeyAndVisible
来显示新屏幕。
用户默认值
目前,您的代码不保证在重新启动之间保存用户默认设置。 UserDefaults
会选择自己的时间将数据保存在磁盘上,如果您在此之前退出您的应用程序,它不会及时保存。
我相信在模拟器上,如果您通过 Xcode 停止 运行 模拟器,总是会发生这种情况。由于这是相当重要的行为,您可能需要调用 UserDefaults.standard.synchronize
来强制保存。
请注意,此呼叫通常会在特定时间间隔自动为您完成;你明确地这样做是因为你不能错过它。