您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS UITabBarController 組件用法詳解:從 xib 搭建到滑動切換

編輯:iOS 開發綜合

UITabBarController 幾乎是 App 主框架的事實標準。底部一排標籤、點擊切換頂部內容,超過五個自動收進 More——這些行為系統都替你做好了。本文從零開始,用 xib 手動搭一個完整的 tab 框架,再補上滑動切換與自定義 item 的細節。

一、先看看它長什麼樣

這是最典型的雛形,如今大約七成應用的主界面結構都是這個樣子。Android 上一般用 ActivityGroup 或 Fragment 加容器來實現同等效果——一個容器裡裝多個子頁面。

Xcode 其實自帶 Tabbed Application 模板:

但模板會直接在代碼裡把子控制器寫死,不利於直觀理解 item、tabBar、圖片文字之間的關係。所以下面我們從空項目開始手動搭一遍,把每一層關係看清楚。

二、步驟一:建立 Empty Application 與 MainWindow.xib

新建工程後,自己添加一個 MainWindow.xib,作為應用啟動時加載的首個 nib。命名可以自定,但沿襲慣例比較好;模板類型選 window 即可。

三、步驟二:把 AppDelegate 與 xib 關聯起來

頭文件寫成這樣:

#import <UIKit/UIKit.h>

@interface NonoAppDelegate : UIResponder <UIApplicationDelegate>
{
    UIWindow           *window;
    UITabBarController *tabTarController;
}

// 模板生成時 window 並不帶 IBOutlet,這裡為了在 xib 中統一連線而加上
@property (retain, nonatomic) IBOutlet UIWindow           *window;
@property (retain, nonatomic) IBOutlet UITabBarController *tabTarController;

@end

四、步驟三:設計 xib 結構

打開 MainWindow.xib,會看到 File's Owner、First Responder 以及 Objects 分組(此時只有一個 window)。

先選中 File's Owner,在右側 Identity Inspector 中把 Custom Class 從 NSObject 改成 UIApplication。改完會發現 File's Owner 多出一個 delegate 出口,這就是後續連線的入口。

接著從右側控件庫拖一個 Object 到 Objects 分組下:

這個對象將充當 delegate。我們的 AppDelegate 恰好就是這樣一個角色,所以選中它,把 Custom Class 設為 NonoAppDelegate,然後把 File's Owner 的 delegate 出口連到它身上。

此時點擊這個 AppDelegate 對象,右側 Outlets 面板會列出我們剛纔聲明的兩個出口。window 已經存在,還差一個 UITabBarController——從控件庫拖一個過來,然後把兩個出口分別連到對應對象上。

基礎框架至此完成:

五、步驟四:實現 AppDelegate

#import "NonoAppDelegate.h"

@implementation NonoAppDelegate

@synthesize window;
@synthesize tabTarController;

- (void)dealloc
{
    [self.window release];
    [self.tabTarController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window.backgroundColor   = [UIColor whiteColor];
    self.window.rootViewController = self.tabTarController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end

六、關鍵一步:修改 main.m

此時運行會發現界面一片空白。原因在 main.m:

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([NonoAppDelegate class]));
    }
}

第四個參數直接指定了 AppDelegate 類,於是應用跳過了 MainWindow.xib 的加載流程,xib 裡連線好的 window 和 tabBarController 自然也沒被實例化。

這個參數的含義是「主 nib 文件名」。改法如下:

#import <UIKit/UIKit.h>
#import "NonoAppDelegate.h"

int main(int argc, char *argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, nil);
    }
}

原本第四個參數用來指定 AppDelegate;但我們已經在 MainWindow.xib 中實例化並關聯了一個 delegate 對象,若再指定一次,這個類相當於被創建了兩份。把參數留空,交給 nib 去創建才是正確做法。

七、認識 UITabBarController 的組成

從界面可以推斷出它由三部分構成:一組子控制器的管理容器、底部的切換條 tabBar,以及一個 delegate。

  • Tab Bar 裡放的是一組 Tab Bar Item,每個 item 對應一個 ViewController。
  • First / Second 等即為各 item 對應的子控制器。這裡有個易錯點:拖入 Tab Bar Item 後,通常還要指定它關聯的 XXXController.xib。

並且必須把 Custom Class 從默認的 UIViewController 改為對應的自定義類,否則應用一啟動就會崩潰。

  • item 屬性:可設置 title、系統內置圖標、自定義圖標,以及 badgeValue(標籤右上角那個紅色數字角標)。
  • 超過 5 個:系統會自動追加一個 More 按鈕,點進去以列表形式展示剩餘的 tab。

八、進階:左右滑動切換標籤頁

系統默認只支持點擊切換。想加上滑手勢,可以在每個子控制器(建議放在基類裡統一處理)的 viewDidLoad 中添加:

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(tappedRightButton:)];
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[self.view addGestureRecognizer:swipeLeft];

UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
                                        initWithTarget:self action:@selector(tappedLeftButton:)];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];
[self.view addGestureRecognizer:swipeRight];

再實現兩個帶翻轉動畫的切換方法:

- (IBAction)tappedRightButton:(id)sender
{
    NSUInteger selectedIndex = [self.tabBarController selectedIndex];
    NSArray *aryViewController = self.tabBarController.viewControllers;

    if (selectedIndex < aryViewController.count - 1) {
        UIView *fromView = [self.tabBarController.selectedViewController view];
        UIView *toView   = [[self.tabBarController.viewControllers objectAtIndex:selectedIndex + 1] view];

        [UIView transitionFromView:fromView
                           toView:toView
                         duration:0.5f
                          options:UIViewAnimationOptionTransitionFlipFromRight
                       completion:^(BOOL finished) {
            if (finished) {
                [self.tabBarController setSelectedIndex:selectedIndex + 1];
            }
        }];
    }
}
- (IBAction)tappedLeftButton:(id)sender
{
    NSUInteger selectedIndex = [self.tabBarController selectedIndex];

    if (selectedIndex > 0) {
        UIView *fromView = [self.tabBarController.selectedViewController view];
        UIView *toView   = [[self.tabBarController.viewControllers objectAtIndex:selectedIndex - 1] view];

        [UIView transitionFromView:fromView
                           toView:toView
                         duration:0.5f
                          options:UIViewAnimationOptionTransitionFlipFromLeft
                       completion:^(BOOL finished) {
            if (finished) {
                [self.tabBarController setSelectedIndex:selectedIndex - 1];
            }
        }];
    }
}

這裡有個細節值得注意:先把 setSelectedIndex: 放到動畫完成回調裡執行,而不是動畫前就切。這樣做能避免動畫過程中 tabBar 高亮狀態與內容提前錯位。

九、現代寫法提示

本文的 xib + MainWindow 流程屬於早期(非 ARC、非 Scene)的寫法,理解它對看懂老項目很有幫助。新項目中, UITabBarController 通常在 SceneDelegate(或 AppDelegate)裡用純代碼創建各個子控制器並塞進 viewControllers 數組,再配合 UITabBarItem 的 imageInsets、titlePositionAdjustment 等屬性做視覺微調,可維護性明顯更好。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved