我有两个VC( ViewController,SettingsVC,VC2 )。
我怎样才能打开开关(位于SettingsVC
),当应用程序启动时,它会显示VC2?
默认为 ViewController.swift 。
我试过这段代码,但是当我打开开关时,重启后没有任何反应。
SettingsVC.swift
let isSwitchOn = UserDefaults.standard.set(true, forKey: "isSwitchOn")
@IBOutlet weak var `switch`: UISwitch!
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
}
答案 0 :(得分:1)
当开关改变时,您不会更改UserDefaults
值。您应该将以下IBAction
与IB中的值已更改相关联:
<强> SettingsVC.swift 强>
@IBAction func switchValueChanged(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: "isSwitchOn")
}