How to execute some code after a segue is done?

筅森魡賤 提交于 2019-11-27 13:55:18
New

You can use the UINavigationControllerDelegate protocol and then define:

– navigationController:didShowViewController:animated:

In case you don't want to use the viewDidAppear: method, you could create a custom segue. In the perform method you would use an animation for the transition, and that can have a completion block. You can add the code there after the animation is complete.

clearlight

In Swift, from a UIViewController subclass you can get the UINavigationController instance and set the delegate, in order to be informed about the completion of segues, as shown. Another logical place to track segues might be the AppDelegate.

Example of doing it from a view controller (VC for short):

class MyViewControllerSubclass : UIViewController, UINavigationControllerDelegate {

    func viewDidLoad() {
        self.navigationController.delegate = self
    }

    func navigationController(navigationController: UINavigationController, didShowViewController viewController: UIViewController, animated: Bool) {
        println("Did show VC: \(viewController)")
    }
 }

But that only shows you when the segue to the VC is complete, as would viewWillAppear() or viewDidAppear() delegate methods in the VC being presented; however, they don't inform about when the target VC is un-presented. It will also only work if your View Controller is part of a Navigation Controller stack.

In the VC you're tracking, you could add the following to detect when the VC (and its memory) are deallocated, or override the viewWillDisappear() method.

deinit {
    println(__FUNCTION__, "\(self)")
}

You can use - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

This method will be called right before a segue is performed in the source UIViewController. If you want to do some code in the destination UIViewController you can get the destination viewcontroller of segue.

You can also add this code in the viewdidAppear in the desintation viewController.

you can call a method of destination UIViewController in prepareForSegue method.

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
  NSLog(@"prepareForSegue: %@", segue.identifier);

  if ([segue.identifier isEqualToString:@"Happy"]) {
      [segue.destinationViewController setHappiness:100];
  } else if ([segue.identifier isEqualToString:@"Sad"]) {
      [segue.destinationViewController setHappiness:0];
  }
}

here setHappiness method is of destination Controller and here 100 is passing there. so you can write a method in destination controller and call it here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!