我经常遇到这个问题。根据我的经验,处理这个问题的最好方法是创建一个容器视图控制器,它将表 vc 作为子 vc。
我创建了一个简单的类来管理它。您可以在 IB 中设置 vc。
#import <UIKit/UIKit.h>
@interface ContainerViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIView *contentViewPlaceholderView;
@property (strong, nonatomic) IBOutlet UIViewController *contentViewController;
@end
#import "ContainerViewController.h"
@interface ContainerViewController ()
@property (assign, nonatomic)BOOL isContentVCAdded;
@end
@implementation ContainerViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
[self setup];
}
return self;
}
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super initWithCoder:aDecoder];
if (self) {
[self setup];
}
return self;
}
- (void)setup
{
self.isContentVCAdded = NO;
}
- (void)insertAndShowContentVC
{
[self removeAllChildVCs];
self.contentViewController.view.frame = self.contentViewPlaceholderView.bounds;
[self addChildViewController:self.contentViewController];
[self.contentViewPlaceholderView addSubview:self.contentViewController.view];
[self.contentViewController didMoveToParentViewController:self];
self.isContentVCAdded = YES;
}
- (void)removeAllChildVCs
{
for (UIViewController *vc in self.childViewControllers) {
[vc willMoveToParentViewController:nil];
[vc.view removeFromSuperview];
[vc removeFromParentViewController];
}
}
- (void)setContentViewController:(UIViewController *)contentVC
{
_contentViewController = contentVC;
if (contentVC == nil) {
[self removeAllChildVCs];
}
else {
[self insertAndShowContentVC];
}
}
#pragma mark Lifecycle
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
if (nil != _contentViewController && !self.isContentVCAdded) {
[self insertAndShowContentVC];
}
}
@end
您只需要创建一个contentViewPlaceholderView
(在 IB 或代码中)具有您希望表格视图具有的框架。然后,您只需根据需要创建表 vc 并将其设置contentViewController
为ContainerViewController