在swift中按下按钮后,在segue之前执行一些代码

MNM*_*MNM 5 ios uistoryboardsegue swift xcode7

我有一个按钮进入另一个视图.我想在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
}
Run Code Online (Sandbox Code Playgroud)

Pau*_*w11 7

你有几个选择;

第一种是从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)
}
Run Code Online (Sandbox Code Playgroud)

或者你可以摆脱@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()
   }
}
Run Code Online (Sandbox Code Playgroud)