由於您試圖創建自定義的UITabBarController,因此應該使用容器視圖控制器。要做到這一點:
- 打開你的故事板並添加一個自定義的UIVIewController(我們稱之爲ContainerViewController)。
- 將表示選項卡的UIVIews插入到該控制器中,然後插入另一個UIVIew(*代碼如下),它將佔用屏幕的其餘部分。這就是孩子控制器將用來顯示他們的場景。
- 爲每個場景(子控制器)一個UIViewController你需要,你通常會,並給他們每個人的唯一標識符(身份檢查 - >故事板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。
完美!感謝您的詳細信息和完整的代碼示例 - 這非常有幫助! –
不客氣。我不知道你的選項卡和子控制器有多複雜,所以我給你最少量的代碼來做你想做的事情。最初我在我的應用程序中使用了這個代碼,但在出現了幾個殭屍問題之後,我最終爲每個子控制器和選項卡添加了一個屬性,並且我只對每個實例化了一次。如果您遇到類似問題,請嘗試。 –