您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

iOS 自訂 UITabBarController 實作

編輯:iOS 相關資訊

以下示範如何自訂 UITabBarController,透過在自訂的 TabBar 類別中建立一個自製的底部列,並以 selectedIndex 切換對應的視圖控制器。

TabBar.m 主要程式碼

#import "TabBar.h"
#import "TabBarBase.h"

@interface TabBar ()
{
    UIButton *btn;
}
@property (nonatomic, strong) UIButton *selectedBtn;
@end

@implementation TabBar

-(void)viewWillLayoutSubviews
{
    self.tabBarController.tabBar.hidden = NO; // 隱藏原先的 tabBar

    CGFloat tabBarViewY = self.view.frame.size.height - 49;
    UIView *_tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, tabBarViewY, 320, 49)];
    [_tabBarView setBackgroundColor:[UIColor grayColor]];
    [self.view addSubview:_tabBarView];

    for (int i = 0; i < 2; i++) {
        btn = [[UIButton alloc] init];

        if (i == 1) {
            [btn setTitle:@"草帽一" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        }
        if (i == 0) {
            [btn setTitle:@"草帽二" forState:UIControlStateNormal];
            [btn setTitleColor:[UIColor redColor] forState:UIControlStateSelected];
        }

        CGFloat x = i * _tabBarView.frame.size.width / 2;
        btn.frame = CGRectMake(x, 0, _tabBarView.frame.size.width / 2, _tabBarView.frame.size.height);
        [_tabBarView addSubview:btn];

        // 剛進入時,第一個按鈕為選中狀態
        if (0 == i) {
            btn.selected = YES;
            self.selectedBtn = btn; // 設為選中的按鈕
        }

        btn.tag = i; // 設定標記,方便索引並跳轉到相應視圖
        [btn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)clickBtn:(UIButton *)sender
{
    if (sender.tag == 0) {
        self.selectedIndex = 0;
    }
    if (sender.tag == 1) {
        self.selectedIndex = 1;
    }

    // 1. 先將之前選中的按鈕設為未選中
    self.selectedBtn.selected = NO;
    // 2. 再將當前按鈕設為選中
    sender.selected = YES;
    // 3. 最後把當前按鈕賦值為之前選中的按鈕
    self.selectedBtn = sender;
    // 4. 透過 selectedIndex 參數設定選中了哪個控制器,完成跳轉
}

@end

重點說明:

· 在 viewWillLayoutSubviews 中建立自製的底部列,並透過 tag 標記各按鈕以便索引。

· 點擊按鈕時,先取消舊按鈕的選中狀態、設定新按鈕為選中,最後更新 selectedBtn 參照。

· 透過設定 self.selectedIndex 即可切換到對應的視圖控制器。

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