Swift 3 / Xcode 8.2 - 在 vi​​ewDidLoad 中切换视图不工作

Swift 3 / Xcode 8.2 - switch view in viewDidLoad not working

我想在用户已经登录时切换 ViewController 加载。 问题:当用户等于 "true"...

时,视图没有改变

提前致谢!!

override func viewDidLoad() {
    super.viewDidLoad()

    var user: String?
    user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String

    if user == "true" {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
        self.show(vc!, sender: vc)
    }

    // Do any additional setup after loading the view, typically from a nib.
}

viewDidLoad 方法中删除代码并使用以下方法。

 override func viewDidAppear() {
     guard let user = UserDefaults.standard.string(forKey: "loginSuccessfull"), user == "true" else {
      return
     }
     let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView")!
     self.present(vc, animated: true)
 }

不要在viewDidLoad中写逻辑,而是在呈现当前之前写viewcontroller

例如 如果您想在应用程序启动时检查它,请检查用户是否已登录 didFinishLaunching 方法并相应地设置 rootViewController。

如果想从其他 viewController 显示它,首先检查用户登录状态并相应地显示 viewcontroller 而不是检查 viewDidLoad。

您也可以通过延迟一些操作来呈现viewcontroller。

DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
        // present view contoller
    }

您应该将显示第二个视图控制器的代码放在 viewWillAppear()viewDidAppear() 中。

override func viewDidAppear() {
    super.viewDidAppear()

    var user: String?
    user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String

    if user == "true" {
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
        self.show(vc!, sender: vc)
    }

    // Do any additional setup after loading the view, typically from a nib.
}

原因是在 viewDidLoad() 期间,您的 ViewController 的某些属性尚未定义,还没有准备好呈现另一个 ViewController。

你需要做成Async,不需要任何延迟,就像这样:

 override func viewDidLoad() {
    super.viewDidLoad()

    var user: String?
    user = UserDefaults.standard.value(forKey: "loginSuccessfull") as? String

    DispatchQueue.main.asyncAfter(deadline: .now()) {
        if user == "true" {
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "SecondView") as UIViewController!
            self.show(vc!, sender: vc)
        }
    }

}