【问题标题】:perform segue in viewDidLoad() without navigation controller in Swift在 Swift 中不使用导航控制器在 viewDidLoad() 中执行 segue
【发布时间】:2014-11-23 20:45:30
【问题描述】:

我有三个视图(视图 1 检查服务器连接,视图 2 显示主要内容,视图 3 显示支持页面)并且我在情节提要中创建它们而无需编码。在启动我的 iOS 应用程序时,视图 1 在检查服务器连接时显示一个微调器。如果连接检查通过,那么我想去查看 2,如果失败,那么我想去查看 3。视图 1 仅用于连接检查,我不想回到这个视图。所以,我认为我不需要导航控制器,或者?

在故事板中,我将所有视图与序列连接起来。在视图 1 的视图控制器中,我这样做:

override func viewDidLoad() {
    super.viewDidLoad()

    let result:Bool = server.isServerAvailable(myURL)

    if (result == true) {
        performSegueWithIdentifier("ConnectionCheckToMain", sender: self)
    }
    else {
        performSegueWithIdentifier("ConnectionCheckToSupport", sender: self)
    }
}

但是viewDidLoad() 函数中的这个segue 不起作用,但我不知道为什么。我在视图上添加了一个按钮来检查它。我已经实现了与viewDidLoad() 中相同的代码,并且运行良好。单击按钮后,将加载下一个视图。

知道为什么代码不起作用吗?

【问题讨论】:

    标签: swift uinavigationcontroller storyboard segue viewdidload


    【解决方案1】:

    此代码使用“segue”为我(Swift 3)解决问题(请将“ConnectionCheckToMain”替换为您的 segue 名称。

    DispatchQueue.main.async(execute: {
      self.performSegue(withIdentifier: "ConnectionCheckToMain", sender: nil)
      })
    

    【讨论】:

      【解决方案2】:

      您可以使用此代码进行导航。

          let vc : UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ConnectionCheckToMain") as! UIViewController;
          self.presentViewController(vc, animated: true, completion: nil)
      

      【讨论】:

      • 谢谢,但现在我收到以下消息:警告:尝试在 上呈现 ,其视图不在窗口层次结构中! 。我的错在哪里?
      • 我解决了问题,我将代码迁移到 viewDidAppear()。
      • 我尝试了这个解决方案,但我得到一个错误 AnyObject 不能转换为 'UIViewController' 你的意思是使用 'as!'强迫沮丧? 为什么?
      • 'Cause Swift 移动到 1.2,现在你必须使用“as”别名强制向下转换。这样! (1.2) = 作为 (1.1)。
      【解决方案3】:

      我遇到了同样的问题,我用这段代码解决了它:

      dispatch_async(dispatch_get_main_queue(), { () -> Void in   
                  let viewController:UIViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ViewControllerClassId") as! ViewControllerClassName
                  self.presentViewController(viewController, animated: true, completion: nil)
              })
      

      【讨论】:

        猜你喜欢
        • 2017-03-03
        • 2019-01-21
        • 1970-01-01
        • 1970-01-01
        • 2017-12-03
        • 2019-10-25
        • 2020-04-24
        • 2018-01-21
        • 2012-01-03
        相关资源
        最近更新 更多