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

问题描述 投票:4回答:3

我有一个按钮进入另一个视图。我想在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
}
ios swift xcode7 uistoryboardsegue
3个回答
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()
   }
}

2
投票

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

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

0
投票

对于Swift 4:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "Segue identifier set in storyboard") {
            // Put your code here
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.