【Objective-C】タブバーの画像、タイトル、文字色を個別に設定する方法【iOS11】【Xcode9】
タブバーの画像、タイトル、文字色を個別に設定し、デザイン性をあげたい場合があります。
タブバーのタイトルの色を一括で変更する方法はよく記載がありますが、個別に設定できる記事が少なかったので記述しておきます。
タブバーの画像、タイトル、文字色の選択、未選択をを個別に設定する方法
まずメソッドを用意します。
- (void)setTabBarItemWithIndex:(int)index
                         title:(NSString *)title
                      offImage:(UIImage *)offImage
                  offTextColor:(UIColor *)offTextColor
                       onImage:(UIImage *)onImage
                   onTextColor:(UIColor *)onTextColor {
    
    UITabBarItem *tabBarItem = [_tabBarController.tabBar.items objectAtIndex:index];
    
    tabBarItem.title = title;
    
    tabBarItem.image = [offImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [tabBarItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:nil size:10],
                                         NSForegroundColorAttributeName : offTextColor}
                              forState:UIControlStateNormal];
    
    tabBarItem.selectedImage = [onImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [tabBarItem setTitleTextAttributes:@{NSFontAttributeName : [UIFont fontWithName:nil size:10],
                                         NSForegroundColorAttributeName : onTextColor}
                              forState:UIControlStateSelected];
}
あとはこんな感じで設定したいタブバーのindexとタブバーのタイトル、未選択時の画像と文字色、選択時の画像と文字色を渡すだけです。
[self setTabBarItemWithIndex:0 title:@"タイトル" offImage:[UIImage imageNamed:@"tab_timer_off.png"] offTextColor:[UIColor lightGrayColor] onImage:[UIImage imageNamed:@"tab_timer_on.png"] onTextColor:[UIColor darkGrayColor]];
とても簡単ですね!
個別に設定するかしないかは別として、あらかじめこのような作りにしておくとあとあと修正も少ないのでできれば最初からこのような作りにしておくといいでしょう!
