我认为最好使用 UISegmentedControl 而不是两个 UIButton。容器视图 subviews ( _vwContainer.subviews
) 最初包含 CatViewController 的视图,自动实例化。
// ViewController.m
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIView *vwContainer;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_vwContainer.clipsToBounds = YES;
}
- (IBAction)onSegmentValueChanged:(UISegmentedControl *)sender {
NSLog(@"Value changed to: %zd",sender.selectedSegmentIndex);
NSLog(@"BEFORE: self.childViewControllers: %@",self.childViewControllers);
NSLog(@"BEFORE: _vwContainer.subviews: %@",_vwContainer.subviews);
// set oldVC & newVC
UIViewController *oldVC = self.childViewControllers.firstObject;
NSString *strIdNewVC;
switch (sender.selectedSegmentIndex) {
case 0: strIdNewVC = @"catVC"; break;
default: strIdNewVC = @"dogVC";
}
UIViewController *newVC = [self.storyboard instantiateViewControllerWithIdentifier:strIdNewVC];
//
[oldVC willMoveToParentViewController:nil];
[self addChildViewController:newVC];
// Prepare animation transition, for example left to right
newVC.view.frame = oldVC.view.frame;
CGPoint pntEnd = oldVC.view.center;
CGPoint pntInit = pntEnd;
pntInit.x += oldVC.view.frame.size.width;
newVC.view.center = pntInit;
[self transitionFromViewController:oldVC toViewController:newVC
duration:0.25 options:0
animations:^{
newVC.view.center = pntEnd;
} completion:^(BOOL finished) {
[oldVC removeFromParentViewController];
[newVC didMoveToParentViewController:self];
NSLog(@"AFTER: self.childViewControllers: %@",self.childViewControllers);
NSLog(@"AFTER: _vwContainer.subviews: %@",_vwContainer.subviews);
}];
}
@end