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

Perform some code before a segue after I push a button in swift

我有一个转到另一个视图的按钮。我想在 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
}

在您的视图控制器中,您可以实现:

override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    if (segue.identifier == "Segue identifier set in storyboard") {
        // Put your code here or call onLogoutClick(null)
    }
}

您有几个选择;

首先是从 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()
   }
}

对于Swift 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "Segue identifier set in storyboard") {
            // Put your code here
        }
    }