你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> [iOS]零碎UITabBarController步驟及自定義

[iOS]零碎UITabBarController步驟及自定義

編輯:IOS開發綜合

關於UITabBarController, 大家都不生疏, 但是有時分又不那麼的熟習, 上面就來再看法一下這個熟習的生疏人.

以下運用微信的tabBar圖標;

一. 零碎UITabBarController根本運用 1.1 根本用法

UITabBarController的運用, 其實很復雜, 這裡直接給出相應代碼:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    // 初始化UITabBarController實例對象
    UITabBarController *tabBar = [[UITabBarController alloc]init];
    // 創立子控制器
    UIViewController *vc1 = [[UIViewController alloc]init];
    vc1.view.backgroundColor = [UIColor redColor];
    // 設置標題
    vc1.tabBarItem.title = @"微信";
    // 設置選中形態的圖片
    vc1.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_mainframeHL"];
    // 設置未選中形態的圖片
    vc1.tabBarItem.image = [UIImage imageNamed:@"tabbar_mainframe"] ;
    // 設置右上角顯示數字(例如: 未讀音訊數目)
    vc1.tabBarItem.badgeValue = @"100";
    // 右上角數字背風光
    vc1.tabBarItem.badgeColor = [UIColor greenColor];

    UIViewController *vc2 = [[UIViewController alloc]init];
    vc2.view.backgroundColor = [UIColor orangeColor];
    vc2.tabBarItem.title = @"聯絡人";
    vc2.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_contactsHL"];
    vc2.tabBarItem.image = [UIImage imageNamed:@"tabbar_contacts"];

    UIViewController *vc3 = [[UIViewController alloc]init];
    vc3.view.backgroundColor = [UIColor cyanColor];
    vc3.tabBarItem.title = @"發現";
    vc3.tabBarItem.image = [UIImage imageNamed:@"tabbar_discover"];
    vc3.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_discoverHL"];

    UIViewController *vc4 = [[UIViewController alloc]init];
    vc4.view.backgroundColor = [UIColor whiteColor];
    vc4.tabBarItem.title = @"我";
    vc4.tabBarItem.image = [UIImage imageNamed:@"tabbar_me"];
    vc4.tabBarItem.selectedImage = [UIImage imageNamed:@"tabbar_meHL"];


    // 添加子視圖到tabbar
    tabBar.viewControllers = @[vc1, vc2, vc3, vc4];

    // 設置為Window跟視圖
    self.Window.rootViewController = tabBar;
    return YES;
}

以上代碼直接寫在xxAppDelegate.m的下面這個辦法裡即可;
效果如下:

[IOS]系統UITabBarController步驟及自定義

留意:這裡運用的是微信的圖標, 是綠色的, 設置完後變成了藍色, 而且下面也沒有設置選中及未選中文字的顏色, 這裡都被默許設置了, 最次要的是沒有顯示我原先圖標的顏色.( 這樣美工是不贊同的 ��).

1.2. 顯示原圖

依據下面的問題, 我們先來看看圖標的問題, 為了不被零碎渲染成藍色, 這裡我們在設置各個控制器的選中和未選中的圖標的時分, 調用一下UIImage的這個辦法即可imageWithRenderingMode:

// 設置選中形態的圖片
    vc1.tabBarItem.selectedImage = [[UIImage imageNamed:@"tabbar_mainframeHL"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    // 設置未選中形態的圖片
    vc1.tabBarItem.image = [[UIImage imageNamed:@"tabbar_mainframe"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

[IOS]系統UITabBarController步驟及自定義
這樣就能正確顯示我們原先的圖片了;

1.3 修正文字顏色

但是文字的顏色並不是我們需求的, 我們可以經過上面的辦法, 來修正文字的顏色:

// 未選中形態下文字顏色
 [vc1.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor redColor]} forState:UIControlStateNormal];
// 選中形態下的文字顏色
 [vc1.tabBarItem setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blueColor]} forState:UIControlStateSelected];

這是設置選中和未選中形態下的標題屬性, 效果如下:

[IOS]系統UITabBarController步驟及自定義
這裡我只是修正了前兩個控制器的文字, 前面的還是用的默許的.
下面是修正按鈕標題的文字屬性, 按鈕右上角的角標的文字屬性, 可運用上面的辦法來修正:

// 未選中形態下的角標文字顏色
[vc1.tabBarItem setBadgeTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]} forState:UIControlStateNormal];
// 選中形態下的角標文字顏色
 [vc1.tabBarItem setBadgeTextAttributes:@{NSForegroundColorAttributeName: [UIColor orangeColor]} forState:UIControlStateSelected];

[iOS]系統UITabBarController步驟及自定義

[iOS]系統UITabBarController步驟及自定義

以上就是零碎自帶UITabBarController及相關屬性的設置, 關於圖標規則的需求根本都能滿足, 假如還有其他的需求, 零碎不能滿足的, 就只能自定義了.

二. 自定義tabBarController

關於自定義的tabBar, 我們普通還是定義為UITabBarController的子類:

@interface LZTabBarController : UITabBarController

這樣我們可以借助UITabBarController的一些屬性和辦法, 例如切換控制器; 不必再去寫切換的邏輯;
實踐上, 我們說的自定義的tabBar, 對數狀況下是自定義的底部的tabBar; 所以, 我們的重點是來設置底部視圖的完成.
我們自定義的時分, 普通有兩種選擇:
- 一種是, 隱藏掉零碎的tabBar, 完全重新規劃;
- 另一種是, 運用零碎的tabBar, 但是自定義tabBarItem

不論是哪一種, 都需求自定義一個tabBarItem, 所以, 先來看看怎樣定義這個tabBarItem;

2.1 自定義item –LZTabBarItem

這個類, 次要做的是規劃item, 及呼應點擊事情

我們定義一個類* LZTabBarItem*, 承繼自UIView, .h聲明文件如下:

//
//  LZTabBarItem.h
//  LZTabBarController
//
//  Created by Artron_LQQ on 2016/12/12.
//  Copyright © 2016年 Artup. All rights reserved.
//

@protocol LZTabBarItemDelegate;
@interface LZTabBarItem : UIView

@property (nonatomic, copy) NSString *icon;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, strong) UIColor *titleColor;

@property (nonatomic, assign) id <LZTabBarItemDelegate> delegate;
@end

@protocol LZTabBarItemDelegate <NSObject>

- (void)tabBarItem:(LZTabBarItem *)item didSelectIndex:(NSInteger)index;
@end

這裡運用代理來回調點擊事情; .m完成如下:

//
//  LZTabBarItem.m
//  LZTabBarController
//
//  Created by Artron_LQQ on 2016/12/12.
//  Copyright © 2016年 Artup. All rights reserved.
//

#import "LZTabBarItem.h"

static NSInteger defaultTag = 100000;
@interface LZTabBarItem ()

@property (nonatomic, strong)UIImageView *iconImageView;
@property (nonatomic, strong)UILabel *titleLabel;
@end

@implementation LZTabBarItem
- (instancetype)init {
    self = [super init];
    if (self) {

        self.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithtarget:self action:@selector(itemClicked:)];
        [self addGestureRecognizer:tap];
    }

    return self;
}
// 重寫setTag辦法
- (void)setTag:(NSInteger)tag {

    [super setTag:tag + defaultTag];
}

- (UIImageView *)iconImageView {
    if (_iconImageView == nil) {
        _iconImageView = [[UIImageView alloc]init];
        _iconImageView.contentMode = UIViewContentModeScaleaspectFit;
        [self addSubview:_iconImageView];
    }

    return _iconImageView;
}

- (UILabel *)titleLabel {
    if (_titleLabel == nil) {
        _titleLabel = [[UILabel alloc]init];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.font = [UIFont systemFontOfSize:10];
        _titleLabel.numberOfLines = 0;
        _titleLabel.textColor = [UIColor grayColor];
        [self addSubview:_titleLabel];
    }

    return _titleLabel;
}

- (void)setIcon:(NSString *)icon {
    _icon = icon;

    self.iconImageView.image = [UIImage imageNamed:icon];
}

- (void)setTitle:(NSString *)title {
    _title = title;

    self.titleLabel.text = title;
}

- (void)setTitleColor:(UIColor *)titleColor {
    _titleColor = titleColor;

    self.titleLabel.textColor = titleColor;
}
- (void)layoutSubviews {
    [super layoutSubviews];

    CGFloat space = 6.0;

    if (self.icon.length > 0 && self.title.length > 0) {

        CGFloat iconHeight = (CGRectGetHeight(self.frame) - space * 3)*2/3.0 ;
        self.iconImageView.frame = CGRectMake(space, space, CGRectGetWidth(self.frame) - 2 * space, iconHeight);
        self.titleLabel.frame = CGRectMake(space, CGRectGetMaxY(self.iconImageView.frame) + space, CGRectGetWidth(self.frame) - 2*space, iconHeight/2.0);
    } else if (self.icon.length > 0) {

        self.iconImageView.frame = CGRectMake(2, 2, CGRectGetWidth(self.frame) - 4, CGRectGetHeight(self.frame) - 4);
    } else if (self.title.length > 0) {

        self.titleLabel.frame = CGRectMake(2, CGRectGetHeight(self.frame) - 22, CGRectGetWidth(self.frame) - 4, 20);
    }
}

- (void)itemClicked:(UITapGestureRecognizer *)tap {

    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBarItem:didSelectIndex:)]) {

        [self.delegate tabBarItem:self didSelectIndex:self.tag - defaultTag];
    }
}
/*
// Only override drawRect: if you perform custom draWing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

其實, 很復雜, 只是添加了一個imageView, 一個label, 和一個單擊手勢來呼應點擊事情. 這裡我是在* layoutSubviews*辦法裡來規劃子視圖的, 這樣當視圖frame改動的時分, 其子視圖會做相應的調整;
這樣,tabBarItem的自定義就完成了,接上去就是自定義tabBar;
tabBar的定義, 有兩種辦法:
- 一個是承繼自UIView, 完全自定義;
- 一個是承繼自UITabBar;

2.2 承繼自UIView

先來看一下承繼自UIView, 完全自定義的辦法:

//
//  LZTabBar.h
//  LZTabBarController
//
//  Created by Artron_LQQ on 2016/12/12.
//  Copyright © 2016年 Artup. All rights reserved.
//

#import <UIKit/UIKit.h>

@class LZTabBarItem;
@protocol LZTabBarDelegate;
@interface LZTabBar : UIView

@property (nonatomic, strong)NSArray<LZTabBarItem *> *items;
@property (nonatomic, assign)id <LZTabBarDelegate> delegate;
@end

@protocol LZTabBarDelegate <NSObject>

- (void)tabBar:(LZTabBar *)tab didSelectItem:(LZTabBarItem *)item atIndex:(NSInteger)index ;
@end

這裡是.h文件內容, 其屬性比擬復雜, 只設置了delegate和items;
.m的完成如下:

//
//  LZTabBar.m
//  LZTabBarController
//
//  Created by Artron_LQQ on 2016/12/12.
//  Copyright © 2016年 Artup. All rights reserved.
//

#import "LZTabBar.h"
#import "LZTabBarItem.h"

@interface LZTabBar ()<LZTabBarItemDelegate>

@property (nonatomic, strong) UIVisualEffectView *effectView;
@property (nonatomic, strong) UIView *topLine;
@end
@implementation LZTabBar

- (instancetype)init {
    self = [super init];
    if (self) {

        self.backgroundColor = [UIColor whiteColor];
    }

    return self;
}
- (UIView *)topLine {
    if (_topLine == nil) {
        _topLine = [[UIView alloc]init];
        _topLine.backgroundColor = [UIColor grayColor];
        [self addSubview:_topLine];
    }

    return _topLine;
}

- (UIVisualEffectView *)effectView {
    if (_effectView == nil) {

        UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
        _effectView.alpha = 1.0;
        [self addSubview:_effectView];
    }

    return _effectView;
}

- (void)layoutSubviews {
    [super layoutSubviews];


    self.effectView.frame = self.bounds;

    [self setupItems];

    self.topLine.frame = CGRectMake(0, 0, CGRectGetWidth(self.frame), 0.6);
}

- (void)setupItems {

    CGFloat width = CGRectGetWidth(self.frame)/self.items.count;
    CGFloat height = CGRectGetHeight(self.frame);

    for (int i = 0; i < self.items.count; i++) {

        LZTabBarItem *item = [self.items objectAtIndex:i];
        item.frame = CGRectMake(i*width, 0, width, height);
        [self addSubview:item];
        item.delegate = self;
    }
}

- (void)tabBarItem:(LZTabBarItem *)item didSelectIndex:(NSInteger)index {

    if (self.delegate && [self.delegate respondsToSelector:@selector(tabBar:didSelectItem:atIndex:)]) {

        [self.delegate tabBar:self didSelectItem:item atIndex:index];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

這個類的次要作用是: 規劃各個item, 在tabBar的地位, 及tabBar的一些內容.

接上去, 就是定義LZTabBarController了;

2.3 自定義LZTabBarController

這個類的次要作用是: 提供數據源, 繪制底部tabBar, 及關聯viewController;

在提供數據的時分, 我獨自設置了一個類類貯存這些數據, 而沒有直接設置為* LZTabBarController*的屬性:

#pragma mark - LZTabBarConfig
@interface LZTabBarConfig : NSObject

/**
 控制器數組, 必需設置
 */
@property (nonatomic, strong) NSArray *viewControllers;

/**
 item標題數組, 選擇設置
 */
@property (nonatomic, strong) NSArray *titles;

/**
 能否是導航, 默許 YES
 */
@property (nonatomic, assign) BOOL isNavigation;

/**
 選中形態下的圖片數組
 */
@property (nonatomic, strong) NSArray *selectedImages;

/**
 正常形態下的圖片數組
 */
@property (nonatomic, strong) NSArray *normalImages;

/**
 選中形態下的標題顏色 默許: red
 */
@property (nonatomic, strong) UIColor *selectedColor;

/**
 正常形態下的標題顏色 默許: gray
 */
@property (nonatomic, strong) UIColor *normalColor;
@end

提供數據源的時分, 只需求配置這個config即可;
其.m文件, 只是設置了一些默許值:

@implementation LZTabBarConfig
- (instancetype)init {
    self = [super init];
    if (self) {

        _isNavigation = YES;
        _normalColor = [UIColor grayColor];
        _selectedColor = [UIColor redColor];
    }

    return self;
}
@end

上面, 回到* LZTabBarController*, 其.h的聲明, 就簡約許多:

#import <UIKit/UIKit.h>

@class LZTabBarConfig;
typedef LZTabBarConfig*(^tabBarBlock)(LZTabBarConfig *config);
@interface LZTabBarController : UITabBarController

/**
 能否可用自動旋轉屏幕
 */
@property (nonatomic, assign) BOOL isAutoRotation;

/**
 創立tabBarController

 @param block 配置創立tabBarController所需的參數
 @return 前往tabBarController實例對象
 */
+ (instancetype)createTabBarController:(tabBarBlock)block;

/**
 獲取以後的tabBarController實例, 實例創立後可經過此辦法獲取以後實例

 @return 前往tabBarController實例對象
 */
+ (instancetype)defaultTabBarController;

/**
 隱藏底部tabBar的辦法

 @param isAnimation 能否需求動畫
 */
- (void)hiddenTabBarWithAnimation:(BOOL)isAnimation;

/**
 顯示底部tabBar的辦法

 @param isAnimation 能否需求動畫
 */
- (void)showTabBarWithAnimation:(BOOL)isAnimation;
@end

只是提供了創立的辦法, 及獲取以後實例和隱藏/顯示底部tabBar的辦法;
.m中的完成:

//
//  LZTabBarController.m
//  LZTabBarController
//
//  Created by Artron_LQQ on 2016/12/12.
//  Copyright © 2016年 Artup. All rights reserved.
//

#import "LZTabBarController.h"
#import "LZTabBar.h"

static CGFloat lzTabBarHeight = 49.0;
@interface LZTabBarController ()<LZTabBarDelegate>

@property (nonatomic, strong) LZTabBar *customTabBar;
@property (nonatomic, strong) LZTabBarConfig *config;
@end

@implementation LZTabBarController
- (LZTabBar *)customTabBar {

    if (_customTabBar == nil) {
        _customTabBar = [[LZTabBar alloc]init];
        _customTabBar.delegate = self;
    }

    return _customTabBar;
}

+ (instancetype)createTabBarController:(tabBarBlock)block {
    static dispatch_once_t onceToken;
    static LZTabBarController *tabBar;
    dispatch_once(&onceToken, ^{

        tabBar = [[LZTabBarController alloc]initWithBlock:block];
    });

    return tabBar;
}

+ (instancetype)defaultTabBarController {

    return [LZTabBarController createTabBarController:nil];
}

- (void)hiddenTabBarWithAnimation:(BOOL)isAnimation {

    if (isAnimation) {

        [UIView animateWithDuration:0.2 animations:^{

            self.customTabBar.alpha = 0;
        }];
    } else {

        self.customTabBar.alpha = 0;
    }
}

- (void)showTabBarWithAnimation:(BOOL)isAnimation {

    if (isAnimation) {

        [UIView animateWithDuration:0.2 animations:^{

            self.customTabBar.alpha = 1.0;
        }];
    } else {

        self.customTabBar.alpha = 1.0;
    }
}

- (instancetype)initWithBlock:(tabBarBlock)block {

    self = [super init];
    if (self) {

        LZTabBarConfig *config = [[LZTabBarConfig alloc]init];

        NSAssert(block, @"Param in zhe function, can not be nil");
        if (block) {

            _config = block(config);
        }

        NSAssert(_config.viewControllers, @"Param 'viewControllers' in the 'config', can not be nil");
        [self setupViewControllers];
        [self setupTabBar];

        _isAutoRotation = YES;
    }

    return self;
}

- (void)setupViewControllers {

    if (_config.isNavigation) {

        NSMutableArray *vcs = [NSMutableArray arrayWithCapacity:_config.viewControllers.count];
        for (UIViewController *vc in _config.viewControllers) {
            if (![vc isKindOfClass:[UINavigationController class]]) {
                UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:vc];
                [vcs addObject:nav];
            } else {
                [vcs addObject:vc];
            }
        }

        self.viewControllers = [vcs copy];
    } else {

        self.viewControllers = [_config.viewControllers copy];
    }
}

- (void)setupTabBar {

    NSMutableArray *items = [NSMutableArray array];
    for (int i = 0; i < _config.viewControllers.count; i++) {
        LZTabBarItem *item = [[LZTabBarItem alloc]init];

        if (i == 0) {

            item.icon = _config.selectedImages[i];
            if (_config.titles.count > 0) {
                item.titleColor = _config.selectedColor;
            }
        } else {

            item.icon = _config.normalImages[i];
            if (_config.titles.count > 0) {

                item.titleColor = _config.normalColor;
            }

        }
        if (i < _config.titles.count) {

            item.title = _config.titles[i];
        }

        [items addObject:item];
        item.tag = i;
    }
    // 隱藏掉零碎的tabBar
    self.tabBar.hidden = YES;
    self.customTabBar.items = [items copy];
    self.customTabBar.frame = CGRectMake(0, CGRectGetHeight(self.view.frame) - lzTabBarHeight, CGRectGetWidth(self.view.frame), lzTabBarHeight);
    [self.view addSubview:self.customTabBar];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = [UIColor whiteColor];
    self.selectedIndex = 0;
}

#pragma mark - LZTabBarDelegate
- (void)tabBar:(LZTabBar *)tab didSelectItem:(LZTabBarItem *)item atIndex:(NSInteger)index {

    NSMutableArray *items = [NSMutableArray arrayWithCapacity:0];
    for (UIView *view in tab.subviews) {
        if ([view isKindOfClass:[LZTabBarItem class]]) {

            [items addObject:view];
        }
    }

    for (int i = 0; i < items.count; i++) {

        UIView *view = items[i];
        if ([view isKindOfClass:[LZTabBarItem class]]) {
            LZTabBarItem *item = (LZTabBarItem *)view;
            item.icon = self.config.normalImages[i];
            if (self.config.titles.count > 0) {

                item.titleColor = _config.normalColor;
            }

        }
    }

    item.icon = self.config.selectedImages[index];

    if (self.config.titles.count > 0) {

        item.titleColor = self.config.selectedColor;
    }

    self.selectedIndex = index;
}

// 屏幕旋轉時調整tabbar
- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id<UIViewControllerTransitionCoordinator>)coordinator {

    [super viewWillTransitionToSize:size withTransitionCoordinator:coordinator];

    self.customTabBar.frame = CGRectMake(0, size.height - lzTabBarHeight, size.width, lzTabBarHeight);
}

- (BOOL)shouldAutorotate {

    return self.isAutoRotation;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (self.isAutoRotation) {

        return UIInterfaceOrientationMaskAllButUpsideDown;
    } else {

        return UIInterfaceOrientationMaskPortrait;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end

這裡次要的其實就是, * setupTabBar*辦法
* LZTabBarDelegate*的代理辦法tabBar:(LZTabBar )tab didSelectItem:(LZTabBarItem )item atIndex:(NSInteger)index, 需求處置一些形態的轉換;
到此, 第一種的自定義就完畢了, 效果如下:

[iOS]系統UITabBarController步驟及自定義

需求留意的是:
由於我們自定義了tabBar , 所以控制器的屬性hidesBottomBarWhenPushed 就得到效果了, 處理的辦法可以是在適宜的中央來調用隱藏/顯示的辦法;
假如, 還想運用零碎的* hidesBottomBarWhenPushed*效果, 可在運用的時分, 調整一下辦法:普通, 我們是直接將tabBarController作為window的rootvc, 然後在其子控制器辨別加上導航, 我們可以做如下調整:
將tabBar作為UINavigationController的rootvc, 然後把這個導航作為window的rootvc:

// 為了可以運用hidesBottomBarWhenPushed, 不直接把tabBar設置為window的跟視圖, 而是設置為導航的rootvc, 然後把導航設置為window的跟視圖
    // 這樣, 在子控制器上就不必再添加導航了, 即設置: config.isNavigation = NO;
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:tab];
// 翻開hidesBottomBarWhenPushed
    nav.hidesBottomBarWhenPushed = YES;
    self.window.rootViewController = nav;

這樣做, 需求留意的是, 其子控制器就不必再添加導航了.

這樣, 就會有下面Gif的效果;
demo地址: LZTabBarController

2.4 承繼自UITabBar

承繼自UITabBar的方式, 與承繼自UIView, 次要的區別是LZTabBar的內容, 其他如LZTabBarItem 和LZTabBarController相關邏輯都是一樣的;

#import <UIKit/UIKit.h>

@class LZTabBarItem;
@protocol LZTabBarDelegate;
@interface LZTabBar : UITabBar

@property (nonatomic, strong)NSArray<LZTabBarItem *> *lzItems;
@property (nonatomic, assign)id <LZTabBarDelegate> lzDelegate;
@end

@protocol LZTabBarDelegate <NSObject>

- (void)tabBar:(LZTabBar *)tab didSelectItem:(LZTabBarItem *)item atIndex:(NSInteger)index ;

@end

.m的完成中, 次要是將零碎的item移除掉, 然後添加上自定義的item:

#import "LZTabBar.h"

@interface LZTabBar ()<LZTabBarItemDelegate>

@end
@implementation LZTabBar

- (instancetype)init {
    self = [super init];
    if (self) {

        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];

    // 移除零碎的tabBarItem
    Class class = NSClassFromString(@"UITabBarButton");
    for (UIView *item in self.subviews) {
        if ([item isKindOfClass:class]) {
            [item removeFromSuperview];
        }
    }
    // 設置自定義的tabBarItem
    [self setupItems];
}

- (void)setupItems {

    CGFloat width = CGRectGetWidth(self.frame)/self.items.count;
    CGFloat height = CGRectGetHeight(self.frame);

    for (int i = 0; i < self.lzItems.count; i++) {

        LZTabBarItem *item = [self.lzItems objectAtIndex:i];
        item.frame = CGRectMake(i*width, 0, width, height);
        [self addSubview:item];
        item.delegate = self;
    }
}

- (void)tabBarItem:(LZTabBarItem *)item didSelectIndex:(NSInteger)index {

    if (self.lzDelegate && [self.lzDelegate respondsToSelector:@selector(tabBar:didSelectItem:atIndex:)]) {

        [self.lzDelegate tabBar:self didSelectItem:item atIndex:index];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end

其最終的效果是一樣的, 只不過我們可以在執行push操作的時分運用控制器的* hidesBottomBarWhenPushed*屬性來隱藏底部的tabBar;

(完)

【[iOS]零碎UITabBarController步驟及自定義】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!

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