在启动时,打开指定的ViewController(iOS)

时间:2017-09-04 16:29:49

标签: ios swift3 xcode8 nsuserdefaults

我有两个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
}

1 个答案:

答案 0 :(得分:1)

当开关改变时,您不会更改UserDefaults值。您应该将以下IBAction与IB中的值已更改相关联:

<强> SettingsVC.swift

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