简体   繁体   中英

Best way to add a UIViewController on top of another UIViewController

What is the best way to add a UIViewController on top of a UIViewController which is already present on my iPhone. There are two ways I know of. But is there a better way? Which one of these is better, if not?

1. [self presentModalViewController:controller animated:NO];
2. [self.view addSubview:someController.view];

This depends on how you want to implement it. If you want to show the view controller and dismiss it using existing transitions, you can use presentModalViewController . But, if you want to show it with some custom animations, you can use addSubView . And again, it entirely depends on you.

[[self view] addSubview: [otherViewController view]];

CGRect frame = [[self view] frame];

int direction = 1;
switch (direction) {
    case 0: // from bottom
        frame.origin.y = [[self view] frame].size.height;
        [[otherViewController view] setFrame: frame];
        frame.origin.y = 0.0 - [[self view] frame].size.height;
        break;
    case 1: // from right
        frame.origin.x = [[self view] frame].size.width;
        [[otherViewController view] setFrame: frame];
        frame.origin.x = 0.0 - [[self view] frame].size.width;
        break;
}

[UIView animateWithDuration: 1.0
                      delay: 0.0
                    options: UIViewAnimationOptionCurveEaseInOut
                 animations:^{
                     [[self view] setFrame: frame];
                 }
                 completion: ^(BOOL finished) {

                 }
];

It's depend on your requirement of showing view controller. There could be one more pushing the controller in navigation stack.

[self.navigationController pushViewController:anotherViewController animated:YES];

Check appl forum post for when to use pushViewController: and when presentModalViewController: .

pushViewController versus presentModalViewController

presentModalViewController vs. pushViewController

Both of the way, are almost equivalent, as the make a stack of views, you can see the beneath view(till not been alkaline) by, [self removeFromSuperview] , when you addSubView , and [self dismissModalViewControllerAnimated:YES]; , when yo use [self presentModalViewController:tempView animated:NO]; , But Yea presentModalViewController , give you default option for animation whether with addSubview , you need to work a bit for that.

Depends on what you want. No one way is better than the other. All are just... ways.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM