具有多个视图的iOS容器

我正在试图创build一个有一个容器的视图。 在该视图上,我想在表视图和地图视图之间切换。 Yelp的应用程序正是我想要做的。

我遇到的问题是在视图之间切换。 这是我的故事板如何设置:

故事板

我创build了一个用于在表和地图之间切换的控制器。 问题是如果我使用模式或自定义的inheritance,它接pipe整个视图。

我尝试将它们embedded导航控制器(我认为)工作,但是一旦用户点击了控制器中的某些东西,我需要将它们从导航控制器中取出,然后导回到主导航中。

一种方法是使SwitchViewController成为自定义容器控制器,并添加表视图或地图视图作为子视图。 这里有一个我之前使用过的与故事板设置相同的例子(我的ContainerViewController是你的SwitchViewController,而我的带有标识符“InitialVC”和“substituteVC”的控制器就是你的表格视图和地图视图)。 这是我在ContainerViewController中的代码,

- (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; UIViewController *initial = [self.storyboard instantiateViewControllerWithIdentifier:@"InitialVC"]; [self addChildViewController:initial]; [self.view addSubview:initial.view]; self.currentController = initial; [self constrainViewEqual:self.currentController]; } -(void)switchToNewView { UIViewController *sub = [self.storyboard instantiateViewControllerWithIdentifier:@"SubstituteVC"]; [self addChildViewController:sub]; sub.view.frame = self.view.bounds; [self moveToNewController:sub]; } -(void)moveToNewController:(UIViewController *) newController { [self.currentController willMoveToParentViewController:nil]; [self transitionFromViewController:self.currentController toViewController:newController duration:.6 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{} completion:^(BOOL finished) { [self.currentController removeFromParentViewController]; [newController didMoveToParentViewController:self]; self.currentController = newController; [self constrainViewEqual:self.currentController]; }]; } 

constrainViewEqual是一个用于为视图设置布局约束的类别方法。 看起来像这样

 -(void)constrainViewEqual:(UIViewController *) vc { [vc.view setTranslatesAutoresizingMaskIntoConstraints:NO]; NSLayoutConstraint *con1 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterX relatedBy:0 toItem:vc.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]; NSLayoutConstraint *con2 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeCenterY relatedBy:0 toItem:vc.view attribute:NSLayoutAttributeCenterY multiplier:1 constant:0]; NSLayoutConstraint *con3 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeWidth relatedBy:0 toItem:vc.view attribute:NSLayoutAttributeWidth multiplier:1 constant:0]; NSLayoutConstraint *con4 = [NSLayoutConstraint constraintWithItem:self.view attribute:NSLayoutAttributeHeight relatedBy:0 toItem:vc.view attribute:NSLayoutAttributeHeight multiplier:1 constant:0]; NSArray *constraints = @[con1,con2,con3,con4]; [self.view addConstraints:constraints]; } 

我从初始视图控制器(您标记为ViewController的那个)中的一个button调用switchToNewView,

 -(IBAction)doStuff:(id)sender { ContainerController *cc = (ContainerController *)self.childViewControllers[0]; [cc switchToNewView]; } 

您可以将新的详细信息viewControllers添加到故事板,并将其大小configuration为与界面构build器中的容器相匹配

在实用程序中选择大小 - 自由形式

然后

在这里你可以指定尺寸

从你的开关视图控制器和新的视图控制器应该只占用该视图的大小。

我希望这有帮助,

干杯,

吉姆