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