下面的代码显示了如何在容器视图中切换控制器。在 IB 中,我从一个选项卡式模板开始,在 FirstViewController 的顶部添加了导航栏和工具栏,并将分段控件添加到工具栏。然后我在视图中添加了一个容器视图(在对象列表中的常规视图旁边),并调整它的大小以占用标签栏和工具栏之间的所有空间。我为容器视图和导航栏的标题项创建了出口,并将方法 changeControllers: 连接到分段控件。当您添加容器视图时,您会自动获得一个相同大小的视图控制器,并使用嵌入转场连接到它。我又添加了两个视图控制器,将它们的大小更改为“自由形式”,并将它们的大小调整为与嵌入式控制器 (320x411) 相同。此大小更改仅用于 IB 中的布局目的,当您将视图添加到容器时,您仍然需要在代码中调整视图大小,如下所示。这段代码在 FirstViewController 中,即带有容器视图的控制器:
@interface FirstViewController ()
@property (weak,nonatomic) IBOutlet UIView *containerView;
@property (strong,nonatomic) UIViewController *embeddedVC;
@property (strong,nonatomic) UIViewController *secondVC;
@property (strong,nonatomic) UIViewController *thirdVC;
@property (strong,nonatomic) UIViewController *currentController;
@property (weak,nonatomic) IBOutlet UINavigationItem *titleItem;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.embeddedVC = self.childViewControllers.lastObject;
self.currentController = self.embeddedVC;
self.titleItem.title = self.currentController.title;
}
-(IBAction)ChangeControllers:(UISegmentedControl *)sender {
switch (sender.selectedSegmentIndex) {
case 0:{
if (![self.currentController isEqual:self.embeddedVC]) {
self.embeddedVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.embeddedVC];
[self moveToNewController:self.embeddedVC];
}
break;
}
case 1:{
if (! self.secondVC) {
self.secondVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Second"];
}
if (![self.currentController isEqual:self.secondVC]) {
self.secondVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.secondVC];
[self moveToNewController:self.secondVC];
}
break;
}
case 2:{
if (! self.thirdVC) {
self.thirdVC = [self.storyboard instantiateViewControllerWithIdentifier:@"Third"];
}
if (![self.currentController isEqual:self.thirdVC]) {
self.thirdVC.view.frame = self.containerView.bounds;
[self addChildViewController:self.thirdVC];
[self moveToNewController:self.thirdVC];
}
break;
}
default:
break;
}
}
-(void)moveToNewController:(id) newController {
[self.currentController willMoveToParentViewController:nil];
[self transitionFromViewController:self.currentController toViewController:newController duration:.6 options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{}
completion:^(BOOL finished) {
[self.currentController removeFromParentViewController];
[newController didMoveToParentViewController:self];
self.currentController = newController;
self.titleItem.title = self.currentController.title;
}];
}