2017-09-04 34 views
0

我有兩個VC(ViewController,SettingsVC,VC2)。在啓動時,打開指定的ViewController(iOS)

我該如何做到這一點,以便當您打開開關(位於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

你不改變UserDefaults值當開關變化。您應該連接以下IBAction價值IB改變

SettingsVC.swift

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

當應用程序啓動時,只寫在didFinishLaunchingWithOptions的VC – BLC