【问题标题】:Why navigation controller does not navigate in callback using Swift?为什么导航控制器不使用 Swift 在回调中导航?
【发布时间】:2015-06-21 21:12:49
【问题描述】:

我创建了一个导航控制器并将其分配给我在 Swift 中的视图控制器。

我创建了以下方法:

@IBAction func btnLoginPressed(sender: AnyObject) {
    let userManager = UserManager()
        userManager.login(txtBoxLogin.text, password: txtBoxPassword.text, operationCompleteHandler: {
            (token: String?) -> Void in
                if let token = token {
                    ApplicationState.ApiToken = token
                    var mainView = self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController
                    self.navigationController!.pushViewController(mainView, animated: true)
                }
        })
}

问题在于它在此配置中不起作用。但是,如果我把

self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController
                    self.navigationController!.pushViewController(mainView, animated: true)

在 operationCompleteHandler 之外它可以完美运行。

我做错了什么,我应该如何解决这个问题?

【问题讨论】:

    标签: swift callback navigation navigationcontroller


    【解决方案1】:

    最后,我找到了这种奇怪行为的原因:回调在与 UI 线程分开的线程上运行。

    为了允许一段代码执行与 UI 相关的事情,您必须使用 dispatch_async() 方法。这是我使用上述方法的工作导航的更新代码:

    @IBAction func btnLoginPressed(sender: AnyObject) {
        let userManager = UserManager()
            userManager.login(txtBoxLogin.text, password: txtBoxPassword.text, operationCompleteHandler: {
                (token: String?) -> Void in
                    if let token = token {
                        ApplicationState.ApiToken = token
                        dispatch_async(dispatch_get_main_queue()) {
                            var mainView = self.storyboard?.instantiateViewControllerWithIdentifier("MenuView") as! MenuViewController
                            self.navigationController!.pushViewController(mainView, animated: true)
                        }
                    }
            })
    }
    

    【讨论】:

    • 不错的发现人。你节省了我几个小时。我仍然在学习。谢谢。
    猜你喜欢
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    相关资源
    最近更新 更多