为什么导航控制器不使用 Swift 在回调中导航?
Why navigation controller does not navigate in callback using Swift?
我创建了一个导航控制器并将其分配给 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 之外它可以完美运行。
我做错了什么,我应该如何解决这个问题?
最后,我找到了这种奇怪行为的原因:回调是 运行 在与 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)
}
}
})
}
我创建了一个导航控制器并将其分配给 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 之外它可以完美运行。
我做错了什么,我应该如何解决这个问题?
最后,我找到了这种奇怪行为的原因:回调是 运行 在与 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)
}
}
})
}