【问题标题】:Perform Segue in ViewDidLoad [duplicate]在 ViewDidLoad 中执行 Segue [重复]
【发布时间】:2018-01-21 01:41:55
【问题描述】:

如果应用程序第一次加载,我会尝试执行 segue。 我可以在调试器中看到我的打印消息,但是 Perform Segue 不起作用。我没有收到任何错误。 有人可以告诉我有什么问题吗?

import UIKit
import LocalAuthentication
let isFirstLaunch = UserDefaults.isFirstLaunch()
extension UserDefaults {
    // check for is first launch - only true on first invocation after app install, false on all further invocations
    // Note: Store this value in AppDelegate if you have multiple places where you are checking for this flag
    static func isFirstLaunch() -> Bool {
        let hasBeenLaunchedBeforeFlag = "hasBeenLaunchedBeforeFlag"
        let isFirstLaunch = !UserDefaults.standard.bool(forKey: hasBeenLaunchedBeforeFlag)
        if (isFirstLaunch) {

            UserDefaults.standard.set(true, forKey: hasBeenLaunchedBeforeFlag)
            UserDefaults.standard.synchronize()
        }
        return isFirstLaunch
    }
}

class loginVC: UIViewController {





    override func viewDidLoad() {

        super.viewDidLoad()

        if  isFirstLaunch == false {
          performSegue(withIdentifier: "setPassword", sender: self)
            print("testFalse") }
            else {
            performSegue(withIdentifier: "setPassword", sender: self)
            print("testTrue")}


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




    }

【问题讨论】:

  • 日志中打印了什么?
  • testTrue 用于首次发布,testFalse 用于其他发布?
  • 正确。日志的第一行是 testFalse
  • override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 被解雇了吗?
  • 显示 segue 在哪里定义?例如,您是否尝试将其移至 viewDidAppear?

标签: ios swift xcode segue viewdidload


【解决方案1】:

您不能在 viewDidLoad() 中使用 performSegue()。将其移至 viewDidAppear()。

在 viewDidLoad() 时,当前视图甚至还没有附加到窗口,所以还不能进行 segue。

【讨论】:

  • 谢谢 Smartcat。将代码移至 ViewDidAppear(),现在可以正常工作了!
  • 可以从 viewWillAppear 调用它你知道吗?对我来说测试没问题,但我担心异常情况或低性能设备......
  • @paul_f 我已经在我的一些生产代码中成功地做到了这一点,但其他人却遇到了麻烦。例如,请参阅此SO。也许这取决于是否要使用过渡动画?如果您从 Apple 中发现了明确的内容,请在此处发布。
  • @Smartcat 你真的让我头疼了。最糟糕的是,我真的很接近,但我以错误的方式处理问题。我试图在viewWillAppear 中运行performSegue。只需将其移至 viewDidAppear 即可解决所有问题。
【解决方案2】:

您还可以使用不同的方法 - 将主窗口的 rootViewController 更改为您选择的视图控制器,具体取决于 isFirstLaunchboolean

UIApplication.shared.keyWindow?.rootViewController = setPasswordViewController

【讨论】:

    猜你喜欢
    • 2012-01-03
    • 2017-12-06
    • 1970-01-01
    • 2014-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多