Skip to content

Instantly share code, notes, and snippets.

@ya-s-u
Created July 2, 2017 03:01
Show Gist options
  • Save ya-s-u/9e732c154111afe8e00823482925c184 to your computer and use it in GitHub Desktop.
Save ya-s-u/9e732c154111afe8e00823482925c184 to your computer and use it in GitHub Desktop.
UITabBar.unselectedItemTintColorをiOS9以下でも使えるようにする
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)
}
}
}
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
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment