OC - Tabbar的選中文字改變顏色


系統默認是 藍色。但是當 tabbarItem的 選中圖標改成了 灰色后,我們也希望把 文字改成 灰色。這個時候就用到了“

setTitleTextAttributes” 方法。

可以在  “ UITabBarItem ” 類的父類 “ UIBarItem ” 類中找到下面這個方法:

/* You may specify the font, text color, and shadow properties for the title in the text attributes dictionary, using the keys found in NSAttributedString.h.

 */

- (void)setTitleTextAttributes:(nullable NSDictionary<NSString *,id> *)attributes forState:(UIControlState)state NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;

這個方法是用來改變 文字的顏色。 可以在 “NSAttributedString.h” 類中找到 Keys.

    // 默認
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];
    [essenceVC.tabBarItem setTitleTextAttributes:attrs forState:UIControlStateNormal];
    
    // 選中
    NSMutableDictionary *attrSelected = [NSMutableDictionary dictionary];
    attrSelected[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attrSelected[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    [essenceVC.tabBarItem setTitleTextAttributes:attrSelected forState:UIControlStateNormal];

 

setTitleTextAttributes 方法 是 “UI_APPEARANCE_SELECTOR ”,以后只要看到 方法名后面有 “UI_APPEARANCE_SELECTOR ”,就代表可以使用 "[UITabBarItem appearance];" 中的 “appearance”。統一設置。

比如說:tabbarController 上面有5個tabbarItem 。這個時候可以寫成:
    // 默認
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attrs[NSForegroundColorAttributeName] = [UIColor grayColor];

    // 選中
    NSMutableDictionary *attrSelected = [NSMutableDictionary dictionary];
    attrSelected[NSFontAttributeName] = [UIFont systemFontOfSize:12];
    attrSelected[NSForegroundColorAttributeName] = [UIColor darkGrayColor];
    

    UITabBarItem *item = [UITabBarItem appearance];
    [item setTitleTextAttributes:attrs forState:UIControlStateNormal];
    [item setTitleTextAttributes:attrSelected forState:UIControlStateNormal];
 
         
         
        

這樣寫完,可以保證5各tabbar的 文字都是統一的。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM