我有一个按钮进入另一个视图。我想在segue移动之前执行一些代码。我面临的问题是在代码有机会完成之前,segue会转到另一页。因此,在更改视图之前,不会更改“用户”默认值中的值。 我的问题是我如何才能运行代码并在完成后让segue开火? 以下是我到目前为止的情况:
@IBAction func onLogoutClick(sender: AnyObject) {
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
//null out everything for logout
email = ""
password = ""
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
//self.view = LoginView
}
答案 0 :(得分:6)
你有几个选择;
第一个是从IB中的按钮中删除动作,然后在UIViewController对象和下一个场景之间创建一个segue;
@IBAction func onLogoutClick(sender: AnyObject) {
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
//null out everything for logout
email = ""
password = ""
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
self.performSegueWithIdentifier("logoutSegue",sender: self)
}
或者你可以摆脱@IBAction方法并实现prepareForSegueWithIdentifier
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "logoutSegue" {
//clear all url chache
NSURLCache.sharedURLCache().removeAllCachedResponses()
//null out everything for logout
email = ""
password = ""
self.loginInformation.setObject(self.email, forKey: "email")
self.loginInformation.setObject(self.password, forKey: "password")
self.loginInformation.synchronize()
}
}
答案 1 :(得分:2)
在视图控制器中,您可以实现:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "Segue identifier set in storyboard") {
// Put your code here or call onLogoutClick(null)
}
}
答案 2 :(得分:0)
对于Swift 4:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "Segue identifier set in storyboard") {
// Put your code here
}
}