iOS-UITabBarController詳細總結(jié)

一、UITabBarController以其相關控件之間的關系

@interface UITabBarController : UIViewController
@property(nonatomic,readonly) UITabBar *tabBar;

@interface UITabBar : UIView
@property(nullable, nonatomic, copy) NSArray<UITabBarItem *> *items;

@interface UITabBarItem : UIBarItem 
@property(nullable, nonatomic,strong) UIImage *selectedImage;
@property(nullable, nonatomic, copy) NSString *badgeValue;
  • UIBarItem
    一個可以放置在Bar之上的所有小控件類的抽象類,可以設置標題,圖片等
  • UITabBarItem
    繼承UIBarItem,增加了selectedunselected時不同狀態(tài)以及badgeValue等屬性,相當于放在TabBar上的特殊“button
  • UITabBar
    NavigaitonBar就是底部的選擇欄 主要對UITabBarItem進行管理 并負責展示底部選擇欄的外觀背景
  • UITabBarController
    包含了viewcontrollers、tabBar等

關系綜述

1、UITabBarController繼承UIViewController,是一個Container;
2、UITabBarController擁有一個readonlyTabBar,TabBar擁有一到多個TabBarItem;
3、每一個TabBarItem需要關聯(lián)一個UIViewController;
這里可以參考IOS-UINavigationController詳解關于UINavigationController等相關控件之間的關系綜述,UITabBarControllerUINavigationController相似。

2、UITabBarController及其相關控件的屬性和方法

1.UITabBarItem

UITabBarItem時一個抽象類,主要負責設置底部每個Item的文字和圖片等屬性。

typedef NS_ENUM(NSInteger, UITabBarSystemItem) {
    UITabBarSystemItemMore,
    UITabBarSystemItemFavorites,
    UITabBarSystemItemFeatured,
    UITabBarSystemItemTopRated,
    UITabBarSystemItemRecents,
    UITabBarSystemItemContacts,
    UITabBarSystemItemHistory,
    UITabBarSystemItemBookmarks,
    UITabBarSystemItemSearch,
    UITabBarSystemItemDownloads,
    UITabBarSystemItemMostRecent,
    UITabBarSystemItemMostViewed,
};
NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBarItem : UIBarItem 
//初始化方法
- (instancetype)init;
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder;
- (instancetype)initWithTitle:(nullable NSString *)title image:(nullable UIImage *)image tag:(NSInteger)tag;
- (instancetype)initWithTitle:(nullable NSString *)title image:(nullable UIImage *)image selectedImage:(nullable UIImage *)selectedImage NS_AVAILABLE_IOS(7_0);
- (instancetype)initWithTabBarSystemItem:(UITabBarSystemItem)systemItem tag:(NSInteger)tag;

//選中的圖片
@property(nullable, nonatomic,strong) UIImage *selectedImage NS_AVAILABLE_IOS(7_0);
//角標
@property(nullable, nonatomic, copy) NSString *badgeValue;

//_____________________________________________IOS7廢除的方法(忽略)______________________________________________________
- (void)setFinishedSelectedImage:(nullable UIImage *)selectedImage withFinishedUnselectedImage:(nullable UIImage *)unselectedImage NS_DEPRECATED_IOS(5_0,7_0);
- (nullable UIImage *)finishedSelectedImage NS_DEPRECATED_IOS(5_0,7_0);
- (nullable UIImage *)finishedUnselectedImage NS_DEPRECATED_IOS(5_0,7_0);
//___________________________________________________________________________________________________

//title的偏移量
@property (nonatomic, readwrite, assign) UIOffset titlePositionAdjustment;
//_____________________________________________IOS10新增的屬性和方法______________________________________________________
//角標顏色
@property (nonatomic, readwrite, copy, nullable) UIColor *badgeColor;
//角標設置富文本
- (void)setBadgeTextAttributes:(nullable NSDictionary<NSString *,id> *)textAttributes forState:(UIControlState)state;
- (nullable NSDictionary<NSString *,id> *)badgeTextAttributesForState:(UIControlState)state;
//___________________________________________________________________________________________________
@end

總結(jié)

  1. 通過初始化方法可以設置title,imageselectedImage等展示的元素。
  2. badgeValue屬性可以在Item的右上角顯示一個數(shù)字角標。
  3. titlePositionAdjustment設置文字的偏移量
  4. iOS10之后,可以通過badgeColor,setBadgeTextAttributes等設置角標的背景色,富文本的角標數(shù)值。
  5. 當UITabBar上的UITabBarItem>=6個時,底部的UITabBar左側(cè)會顯示一個More的Item。

2.UITabBar

一個UITabBarController只有一個TabBar。

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBar : UIView
//代理
@property(nullable, nonatomic, weak) id<UITabBarDelegate> delegate;
//get/set UITabBarItems 默認是nil 改變時沒有動畫效果 按順序展示
@property(nullable, nonatomic, copy) NSArray<UITabBarItem *> *items;
//選中的item
@property(nullable, nonatomic, weak) UITabBarItem *selectedItem;
//設置Items
- (void)setItems:(nullable NSArray<UITabBarItem *> *)items animated:(BOOL)animated;

- (void)beginCustomizingItems:(NSArray<UITabBarItem *> *)items;
- (BOOL)endCustomizingAnimated:(BOOL)animated;
#if UIKIT_DEFINE_AS_PROPERTIES
@property(nonatomic, readonly, getter=isCustomizing) BOOL customizing;
#else
- (BOOL)isCustomizing;
#endif

//ios7之后,
@property(null_resettable, nonatomic, strong) UIColor *tintColor ;
@property(nullable, nonatomic, strong) UIColor *barTintColor ;

//未選中的Item的顏色 IOS10可用
@property (nonatomic, readwrite, copy, nullable) UIColor *unselectedItemTintColor;

//ios8后廢除 使用tintColor
@property(nullable, nonatomic, strong) UIColor *selectedImageTintColor(5_0,8_0);

//背景圖片
@property(nullable, nonatomic, strong) UIImage *backgroundImage;
@property(nullable, nonatomic, strong) UIImage *selectionIndicatorImage;
@property(nullable, nonatomic, strong) UIImage *shadowImage;

//item位置
@property(nonatomic) UITabBarItemPositioning itemPositioning;
//item寬度
@property(nonatomic) CGFloat itemWidth;
//item間隙
@property(nonatomic) CGFloat itemSpacing;
//樣式
@property(nonatomic) UIBarStyle barStyle;
//半透明
@property(nonatomic,getter=isTranslucent) BOOL translucent NS_AVAILABLE_IOS(7_0);
@end

以下是tabBar的代理方法,操作TabBar時的回調(diào),主要是對UITabBarItem的操作

@protocol UITabBarDelegate<NSObject>
@optional
/**
 用戶選中某個UITabBarItem
 */
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item;
//此四個代理方法是當Items>=6個時,當進入More頁面時,開始或結(jié)束Item編輯狀態(tài)的相關回調(diào)
- (void)tabBar:(UITabBar *)tabBar willBeginCustomizingItems:(NSArray<UITabBarItem *> *)items;                    
- (void)tabBar:(UITabBar *)tabBar didBeginCustomizingItems:(NSArray<UITabBarItem *> *)items; 
- (void)tabBar:(UITabBar *)tabBar willEndCustomizingItems:(NSArray<UITabBarItem *> *)items changed:(BOOL)changed; 
- (void)tabBar:(UITabBar *)tabBar didEndCustomizingItems:(NSArray<UITabBarItem *> *)items changed:(BOOL)changed;
@end

3.UITabBarController

NS_CLASS_AVAILABLE_IOS(2_0) @interface UITabBarController : UIViewController <UITabBarDelegate, NSCoding>
//視圖控制器數(shù)組,這個屬性被賦值時,customizableViewControllers屬性的值與之一樣。
@property(nullable, nonatomic,copy) NSArray<__kindof UIViewController *> *viewControllers;
- (void)setViewControllers:(NSArray<__kindof UIViewController *> * __nullable)viewControllers animated:(BOOL)animated;

//當前選中的視圖控制器
@property(nullable, nonatomic, assign) __kindof UIViewController *selectedViewController; 
//與selectedViewController對應
@property(nonatomic) NSUInteger selectedIndex;

//當ViewController的數(shù)量>=6,TabBar會出現(xiàn)一個moreNavigationController管理多余的viewcontroller。readonly屬性
@property(nonatomic, readonly) UINavigationController *moreNavigationController;

//當viewcontroller>=6時,moreNavigationController右上方會有個edit按鈕,支持通過拖拽修改ViewController的順序,如若要屏蔽該功能,customizableViewControllers設置為nil即可。
@property(nullable, nonatomic, copy) NSArray<__kindof UIViewController *> *customizableViewControllers;

//只讀屬性,為了配置UITabBarItem,應該去修改ViewControllers屬性。
@property(nonatomic,readonly) UITabBar *tabBar;

//協(xié)議
@property(nullable, nonatomic,weak) id<UITabBarControllerDelegate> delegate;

@end
//should選中viewController  return YES 可以本選中, NO不可以被選中
- (BOOL)tabBarController:(UITabBarController *)tabBarController shouldSelectViewController:(UIViewController *)viewController;

// 選中viewController后執(zhí)行的Action
- (void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController;

// 將要處于編輯狀態(tài)(即點擊MoreNavigationController的edit按鈕)
- (void)tabBarController:(UITabBarController *)tabBarController willBeginCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers;

// MoreNavigationController will結(jié)束編輯狀態(tài)
- (void)tabBarController:(UITabBarController *)tabBarController willEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed;

//MoreNavigationController did結(jié)束編輯狀態(tài)
- (void)tabBarController:(UITabBarController *)tabBarController didEndCustomizingViewControllers:(NSArray<__kindof UIViewController *> *)viewControllers changed:(BOOL)changed;

//UITabBarController支持的界面方向
- (UIInterfaceOrientationMask)tabBarControllerSupportedInterfaceOrientations:(UITabBarController *)tabBarController;

//對于將要展示的tabBarController 優(yōu)先選擇屏幕方向
- (UIInterfaceOrientation)tabBarControllerPreferredInterfaceOrientationForPresentation:(UITabBarController *)tabBarController;

//自定義轉(zhuǎn)場動畫
- (nullable id <UIViewControllerInteractiveTransitioning>)tabBarController:(UITabBarController *)tabBarController
                      interactionControllerForAnimationController: (id <UIViewControllerAnimatedTransitioning>)animationController;
- (nullable id <UIViewControllerAnimatedTransitioning>)tabBarController:(UITabBarController *)tabBarController
            animationControllerForTransitionFromViewController:(UIViewController *)fromVC
                                              toViewController:(UIViewController *)toVC;

@end
@interface UIViewController (UITabBarControllerItem)
@property(null_resettable, nonatomic, strong) UITabBarItem *tabBarItem;
@property(nullable, nonatomic, readonly, strong) UITabBarController *tabBarController;
@end

3、實際開發(fā)中的相關問題

1. UITabBar的背景顏色

1.直接設置背景顏色
//    self.tabBar.backgroundColor = [UIColor orangeColor];
//    [[UITabBar appearance] setBackgroundColor:[UIColor orangeColor]];
    [[UITabBar appearance]setBarTintColor:[UIColor orangeColor]];
    [UITabBar appearance].translucent = NO

注意:
1.前兩種設置背景顏色的方法是無效的。
2.tabBar是一個readonly屬性,這里不能使用TabBarController.tabBar.barTintColor設置背景色。
前兩種方法是無效的。
3.這里設置tabBar的半透明屬性translucent設置為NO,默認為YES,若保留半透明效果,設置的顏色會與正常的顏色有色差;

2.添加一個有顏色的View
    UIView * view = [UIView new];
    view.backgroundColor = [UIColor orangeColor];
    view.frame = self.tabBar.bounds;
    [[UITabBar appearance] insertSubview:view atIndex:0];
3.使用背景圖片
[[UITabBar appearance] setBackgroundImage:[UIImage imageNamed:@"tabBarBackgroundImage"]];
[UITabBar appearance].translucent = NO;

這里同樣需要設置translucent為NO

2. UITabBar的頂部的shadowImage

[[UITabBar appearance] setShadowImage:[UIImage new]];
[[UITabBar appearance] setBackgroundImage:[[UIImage alloc]init]];

UINavigationBar一樣,需同時設置ShadowImageBackgroundImage才能生效。

3.tabBarItem選中時的背景色

 //    [UITabBar appearance].selectionIndicatorImage = [self drawTabBarItemBackgroundImageWithSize:size];
self.tabBar.selectionIndicatorImage = [self drawTabBarItemBackgroundImageWithSize:size];

此處可直接獲取TabBarControllertabBar直接設置selectionIndicatorImage。
獲取某背景顏色的image的方法可參考IOS-UINavigationController詳解相關方法,注意圖片size要設置正確。

4.修改tabBarItem的文字、圖片顏色

tabBarItem,默認狀態(tài)下,選中狀態(tài)是藍色,未選中狀態(tài)下是灰色。選中狀態(tài)的Item的文字和圖片顏色可直接通過tintColor屬性修改

self.tabBar.tintColor = [UIColor yellowColor];

現(xiàn)實中,往往都是現(xiàn)實圖片實際的顏色。我們可以通過自定義一個tabBarItem繼承UITabBarItem,在initWithCoder方法添加以下代碼完成現(xiàn)實圖片實際顏色的效果。

-(id)initWithTitle:(NSString *)title image:(UIImage *)image selectedImage:(UIImage *)selectedImage{
    if (self = [super initWithTitle:title image:image selectedImage:selectedImage]) {
        self.image = [self.image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        self.selectedImage = [self.selectedImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
        
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName : [self mostColorWithImage:self.image]}
                            forState:UIControlStateNormal];
        
        [self setTitleTextAttributes:@{NSForegroundColorAttributeName : [self mostColorWithImage:self.selectedImage]}
                            forState:UIControlStateSelected];
    }
    return self;
}

-(UIColor*)mostColorWithImage:(UIImage *)image
{
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_6_1
    int bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedLast;
#else
    int bitmapInfo = kCGImageAlphaPremultipliedLast;
#endif
    
    //第一步 先把圖片縮小 加快計算速度. 但越小結(jié)果誤差可能越大
    CGSize thumbSize=CGSizeMake(50, 50);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGContextRef context = CGBitmapContextCreate(NULL,
                                                 thumbSize.width,
                                                 thumbSize.height,
                                                 8,//bits per component
                                                 thumbSize.width*4,
                                                 colorSpace,
                                                 bitmapInfo);
    
    CGRect drawRect = CGRectMake(0, 0, thumbSize.width, thumbSize.height);
    CGContextDrawImage(context, drawRect, image.CGImage);
    CGColorSpaceRelease(colorSpace);
    
    
    //第二步 取每個點的像素值
    unsigned char* data = CGBitmapContextGetData (context);
    
    if (data == NULL) return nil;
    
    NSCountedSet *cls = [NSCountedSet setWithCapacity:thumbSize.width*thumbSize.height];
    
    for (int x=0; x<thumbSize.width; x++) {
        for (int y=0; y<thumbSize.height; y++) {
            
            int offset = 4*(x*y);
            
            int red = data[offset];
            int green = data[offset+1];
            int blue = data[offset+2];
            int alpha =  data[offset+3];
            
            if (alpha != 255) continue;
            
            NSArray *clr=@[@(red),@(green),@(blue),@(alpha)];
            [cls addObject:clr];
            
        }
    }
    CGContextRelease(context);
    
    
    //第三步 找到出現(xiàn)次數(shù)最多的那個顏色
    NSEnumerator *enumerator = [cls objectEnumerator];
    NSArray *curColor = nil;
    
    NSArray *MaxColor=nil;
    NSUInteger MaxCount=0;
    
    while ( (curColor = [enumerator nextObject]) != nil )
    {
        NSUInteger tmpCount = [cls countForObject:curColor];
        
        if ( tmpCount < MaxCount ) continue;
        
        MaxCount=tmpCount;
        MaxColor=curColor;
    }
    
    return [UIColor colorWithRed:([MaxColor[0] intValue]/255.0f) green:([MaxColor[1] intValue]/255.0f) blue:([MaxColor[2] intValue]/255.0f) alpha:1.0 ];
}

iOS10之后新增了unselectedItemTintColor設置未選中狀態(tài)下的item顏色。配合tintColor可以達到我們需要的大部分效果。

5.修改TabBar的高度

UITabBarController里重寫viewWillLayoutSubviews

- (void)viewWillLayoutSubviews {
    CGRect tabFrame = self.tabBar.frame;
    tabFrame.size.height = 59;
    tabFrame.origin.y = self.view.bounds.size.height - 59;
    self.tabBar.frame = tabFrame;
}

然后通過UITabBarItemimageInsetstitlePositionAdjustment屬性調(diào)整圖片和文字的位置

for (UITabBarItem * item in self.tabBar.items) {
        item.imageInsets = UIEdgeInsetsMake(8, 0, -8, 0);
    }
[[UITabBarItem appearance]setTitlePositionAdjustment:UIOffsetMake(0, -8)];

6. 自定義UITabBarController

具體內(nèi)容參考:仿閑魚自定義Tabbar(純代碼)

參考文章
iOS UI Tab開發(fā)
UITabBarController的使用
UITabBarController、TabBar背景顏色設置、TabBarItem顏色處理

結(jié)束語:

此文是我在學習過程中的探索與總結(jié),不足之處還望大家見諒,并歡迎指正!
愿每一個人都能學有所成!

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容