最后,我对我在问题中所说的内容采取了不同的方法,因为我觉得使用故事板标识符有点“丑陋”且不正确,因为视图没有任何转义。
所以这就是我所做的:
我首先使用 XIB 文件为将在容器视图中显示的视图控制器创建类。(例如 FirstController、SecondController 等)
然后我把它放在我的 ViewController 的 ViewDidLoad 方法中(父视图控制器 - 带有分段控件的那个)
- (void)viewDidLoad
{
[super viewDidLoad];
// First Controller
self.firstViewController = [[FirstViewController alloc] init];
// Second Controller
self.secondViewController = [[SecondViewController alloc] init];
// Add the controllers to an Array
self.controllers = @[self.firstViewController, self.secondViewController];
// Set the container to show the first view controller on load
[self displayContentController:[self.controllers firstObject]];
}
然后我设置了三个方法来处理容器视图的视图的显示和隐藏
- (void)displayContentController:(UIViewController *)content
{
[self addChildViewController:content];
content.view.frame = [self frameForContentController];
[self.view addSubview:content.view];
[content didMoveToParentViewController:self];
// Set current controller
self.currentController = content;
}
- (void)hideContentController: (UIViewController*)content
{
[content willMoveToParentViewController:nil];
[content.view removeFromSuperview];
[content removeFromParentViewController];
}
- (CGRect)frameForContentController
{
return self.contentController.frame;
}
Then finally, I handled the event when a different segmented control value is selected.
- (IBAction)segmentedControlValueChanged:(UISegmentedControl *)sender
{
// Hide current view controller
[self hideContentController:self.currentController];
// Show new selected view controller
[self displayContentController:[self.controllers objectAtIndex:sender.selectedSegmentIndex]];
}
希望这可以帮助。