LoginSignup
2
2

More than 5 years have passed since last update.

UITabBar.unselectedItemTintColor を iOS9 以下でも使えるようにする

Last updated at Posted at 2017-07-02

UITabBarの非選択時の色を指定したい時、iOS10からはvar unselectedItemTintColor: UIColor?というプロパティが使えます。

これをOSのバージョンを意識せずに使えるようになるExtensionです。

UITabBar+.swift
import UIKit

extension UITabBar {

    private struct AssociatedKey {
        static var unselectedItemTintColor = "UITabBar.UnselectedItemTintColor"
    }

    @nonobjc
    var unselectedItemTintColor: UIColor? {
        get {
            return objc_getAssociatedObject(self, &AssociatedKey.unselectedItemTintColor) as? UIColor
        }
        set {
            objc_setAssociatedObject(self, &AssociatedKey.unselectedItemTintColor, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)

            if let color = newValue {
                setUnselectedItemTintColor(color)
            }
        }
    }

    private func setUnselectedItemTintColor(_ color: UIColor) {
        items?.forEach {
            $0.image = $0.image?.withRenderingMode(.alwaysOriginal)
            $0.setTitleTextAttributes([NSForegroundColorAttributeName: color], for: .normal)
            $0.setTitleTextAttributes([NSForegroundColorAttributeName: tintColor], for: .selected)
        }
    }
}

このように、#availableで分岐せずに使え、タブ非選択時には元画像の色で表示されます。

ViewController.swift
import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var tabBar: UITabBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        tabBar.selectedItem = tabBar.items?.first
        tabBar.tintColor = .red
        tabBar.unselectedItemTintColor = .blue
    }
}

うーん...🤔
これだとただ上書きしてるだけな気がするから微妙かも...
objcだったらバージョンによって動的にプロパティ追加できて、良さそう💡

参考

http://techblog.kayac.com/8_ios_version.html
http://bricklife.hatenablog.com/entry/2012/03/19/130011
http://bricklife.hatenablog.com/entry/2011/12/20/092539

2
2
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
2
2