9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

UITabBarのバッジの背景色を変更する

Last updated at Posted at 2016-07-10

UITabBarは各タブアイコンの右上にバッジを表示できる。
スクリーンショット 2016-07-10 15.42.13.png

バッジの表示内容に対する変更は badgeValue を変更することで可能だが、その背景色を変更する手段は用意されていない。
その背景色を変更するメソッドを書いた。

func tabbaredit(color:UIColor){
    let tabbar = self.tabBarController!.tabBar
    // search badgeView
    for barButton in tabbar.subviews{
        for buttonSubView in barButton.subviews{
            if NSStringFromClass(buttonSubView.dynamicType) == "_UIBadgeView"{
                buttonSubView.backgroundColor = color
                buttonSubView.layer.cornerRadius = buttonSubView.frame.size.height/2
                for badgeView in buttonSubView.subviews{
                    // change badge background color
                    if NSStringFromClass(badgeView.dynamicType) == "UILabel"{
                        let label:UILabel = badgeView as! UILabel
                        label.backgroundColor = color
                        label.layer.cornerRadius = label.frame.size.height/2
                    }
                    // remove _UIBadgeBackground
                    if NSStringFromClass(badgeView.dynamicType) == "_UIBadgeBackground"{
                        badgeView.hidden = true
                    }
                }
            }
        }
    }
}

上記メソッドをbadgeValueを変更した直後に呼び出す。
すると、下記のようにバッジの背景色が変更される。

スクリーンショット 2016-07-10 15.42.22.png スクリーンショット 2016-07-10 15.43.10.png

少し応用すれば文字色も変更可能。

テストで使用したソース

参考

http://qiita.com/satomikko94/items/3623f8d56e17513579d6
https://github.com/nst/iOS-Runtime-Headers/blob/master/Frameworks/UIKit.framework

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?