由于您正在尝试创建自定义 UITabBarController,因此您应该使用容器视图控制器。要做到这一点:
- 打开你的故事板并添加一个自定义 UIVIewController(我们称之为 ContainerViewController)。
- 将代表您的选项卡的 UIVIews 插入该控制器,然后插入另一个 UIVIew(下面代码中的 *currentView),它将占据屏幕的其余部分。这就是子控制器将用来显示他们的场景的内容。
- 像往常一样为您需要的每个场景(子控制器)创建一个 UIVIewController,并为每个场景提供一个唯一标识符(Identity Inspector -> Storyboard ID)
现在您必须在 ContainerViewController 中添加以下代码:
@interface ContainerViewController ()
@property (strong, nonatomic) IBOutlet UIView *currentView; // Connect the UIView to this outlet
@property (strong, nonatomic) UIViewController *currentViewController;
@property (nonatomic) NSInteger index;
@end
@implementation ContainerViewController
// This is the method that will change the active view controller and the view that is shown
- (void)changeToControllerWithIndex:(NSInteger)index
{
if (self.index != index){
self.index = index;
[self setupTabForIndex:index];
// The code below will properly remove the the child view controller that is
// currently being shown to the user and insert the new child view controller.
UIViewController *vc = [self setupViewControllerForIndex:index];
[self addChildViewController:vc];
[vc didMoveToParentViewController:self];
if (self.currentViewController){
[self.currentViewController willMoveToParentViewController:nil];
[self transitionFromViewController:self.currentViewController toViewController:vc duration:0 options:UIViewAnimationOptionTransitionNone animations:^{
[self.currentViewController.view removeFromSuperview];
[self.currentView addSubview:vc.view];
} completion:^(BOOL finished) {
[self.currentViewController removeFromParentViewController];
self.currentViewController = vc;
}];
} else {
[self.currentView addSubview:vc.view];
self.currentViewController = vc;
}
}
}
// This is where you instantiate each child controller and setup anything you need on them, like delegates and public properties.
- (UIViewController *)setupViewControllerForIndex:(NSInteger)index {
// Replace UIVIewController with your custom classes
if (index == 0){
UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"STORYBOARD_ID_1"];
return child;
} else {
UIViewController *child = [self.storyboard instantiateViewControllerWithIdentifier:@"STORYBOARD_ID_2"];
return child;
}
}
// Use this method to change anything you need on the tabs, like making the active tab a different colour
- (void)setupTabForIndex:(NSInteger)index{
}
// This will recognize taps on the tabs so the change can be done
- (IBAction)tapDetected:(UITapGestureRecognizer *)gestureRecognizer {
[self changeToControllerWithIndex:gestureRecognizer.view.tag];
}
最后,您创建的每个代表选项卡的视图都应该有它自己的 TapGestureRecognizer 和它的标签的数字。
通过执行所有这些操作,您将拥有一个带有所需按钮的控制器(它们不必是可重复使用的),您可以在其中添加尽可能多的功能(这将使用 setupTabBarForIndex: 方法)并且您赢了不要违反 DRY。