How to execute some code after a segue is done?

2019-01-11 12:35发布

问题:

Is it possible in iOS 6 to know when a UIStoryboardSegue has finished its transition? Like when i add a UIStoryboardSegue from UIButton to push another UIViewController on the navigationcontroler, i want to to something right after the push-transition is finished.

回答1:

You can use the UINavigationControllerDelegate protocol and then define:

– navigationController:didShowViewController:animated:


回答2:

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.



回答3:

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)")
}


回答4:

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.



回答5:

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