[iOS] The difference between push and present Controller


Preface

There are two ways to launch and exit the interface in iOS - push and present. Next, the author will introduce these two methods respectively.


1. push method

    SecondViewController *second = [[SecondViewController alloc] init];
    [self.navigationController pushViewController:second animated:YES];

2. pop method

	//返回上一级
	[self.navigationController popViewControllerAnimated:YES];

	//返回根视图
	[self.navigationController popToRootViewControllerAnimated:YES];

	//返回指定级数 (objectAtIndex:参数为想要返回的级数)
	[self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:0]  animated:YES];

3. present method

    SecondViewController *second = [[SecondViewController alloc] init];
    [self presentViewController:second animated:YES completion:nil];

4. Dismiss method

    [self dismissViewControllerAnimated:YES completion:nil];

5. Dismiss multi-level method

presentedViewController and presentingViewController are two properties in UIViewController.
The difference between PresentedViewController and PresentingViewController

presentedViewController: The view controller that was presented by this
view controller or its nearest ancestor.
presentingViewController: The view controller that presented this view
controller (or its farthest ancestor.) The view controller for this view controller (or its most distant ancestor).

Assume that controller A jumps to controller B through presentation, then A.presentedViewController is controller B;
B.presentingViewController is controller A;


Example

Create four pages ABCD. For example, if we want to go from D->A, we can use the following method:

    UIViewController *rootVC = self.presentingViewController;
     while  (rootVC. presentingViewController ) {
    
    
              rootVC = rootVC.presentingViewController ;
             }
    [rootVC dismissViewControllerAnimated:YES completion:nil];

For example, if we want to go from D->B, we can use presenting to jump to the page.

    [self.presentingViewController.presentingViewController dismissViewControllerAnimated:YES completion:nil];

The following code can also implement D->B

    UIViewController *rootVC =  self.presentingViewController;
    while (![rootVC isKindOfClass:[SecondViewController class]])  {
    
    
        rootVC = rootVC.presentingViewController;
    }
    [rootVC dismissViewControllerAnimated:YES completion:nil];

animation

Insert image description here

おすすめ

転載: blog.csdn.net/weixin_72437555/article/details/132817871