首页 > 解决方案 > 是否可以将表视图控制器添加到视图控制器的一部分?

问题描述

假设我有一个UITableViewController,它大部分是可重用的,应该从许多UIViewController中使用,但它应该只覆盖整个视图的一部分(例如总高度的 90%)。通常我会用导航来做到这一点,但如果我想保持 UIViewController 的前 10% 可见,并为剩余的 90% 显示UITableViewController,这是可能的,如果是的话怎么做?

标签: iosuiviewcontrolleruinavigationcontroller

解决方案


是的。大视图控制器是容器视图控制器,小视图控制器(在这种情况下是表视图控制器)是子视图控制器。我们可以在容器视图控制器中添加或移除子视图控制器。

将子视图控制器添加到容器

- (void)displayContentController:(UIViewController *)content {
   [self addChildViewController:content];
   content.view.frame = [self frameForContentController];
   [self.view addSubview:self.currentClientView];
   [content didMoveToParentViewController:self];
}

从容器中移除子视图控制器

- (void)hideContentController:(UIViewController *)content {
   [content willMoveToParentViewController:nil];
   [content.view removeFromSuperview];
   [content removeFromParentViewController];
}

我们也可以同时移除一个旧的子视图控制器并添加一个新的子视图控制器。这是示例代码(带动画)。

- (void)cycleFromViewController:(UIViewController *)oldVC
               toViewController:(UIViewController *)newVC {
   // Prepare the two view controllers for the change.
   [oldVC willMoveToParentViewController:nil];
   [self addChildViewController:newVC];

   // Get the start frame of the new view controller and the end frame
   // for the old view controller. Both rectangles are offscreen.
   newVC.view.frame = [self newViewStartFrame];
   CGRect endFrame = [self oldViewEndFrame];

   // Queue up the transition animation.
   [self transitionFromViewController:oldVC toViewController:newVC
        duration:0.25 options:0
        animations:^{
            // Animate the views to their final positions.
            newVC.view.frame = oldVC.view.frame;
            oldVC.view.frame = endFrame;
        }
        completion:^(BOOL finished) {
           // Remove the old view controller and send the final
           // notification to the new view controller.
           [oldVC removeFromParentViewController];
           [newVC didMoveToParentViewController:self];
        }];
}

推荐阅读