使用tabBarItem.setTitleTextAttributes 更改各个条形项目的文本颜色。
把这个放在每个选项卡的viewDidLoad 方法中:
self.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.red()], for:.selected)
要同时更改图标和文本的色调颜色,一个简单的解决方案是在每个选项卡的 viewWillAppear 方法中更改 tabBar 的色调颜色:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.tabBar.tintColor = UIColor.red()
}
改变图像色调颜色的另一种解决方案是为 UIImage 创建一个扩展,并使用它来更改具有自定义色调的选定图像:
extension UIImage {
func tabBarImageWithCustomTint(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context: CGContext = UIGraphicsGetCurrentContext()!
context.translate(x: 0, y: self.size.height)
context.scale(x: 1.0, y: -1.0)
context.setBlendMode(CGBlendMode.normal)
let rect: CGRect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
context.clipToMask(rect, mask: self.cgImage!)
tintColor.setFill()
context.fill(rect)
var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
newImage = newImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
return newImage
}
}
使用此代码更改所选图像:
self.tabBarItem.selectedImage = self.tabBarItem.selectedImage?.tabBarImageWithCustomTint(tintColor: UIColor.red())