在 Swift 2 中,我在 Storyboard 中使用了一个用户定义的运行时属性,其关键路径为 tintColor 来更改选项卡栏项目图标的颜色。但是,似乎 tintColor 已随 Swift 3 一起删除。如何在 Swift 3 的选项卡栏 Controller 中更改选项卡栏项目的选定颜色?
谢谢!
编辑:附截图
最佳答案
使用 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())
关于ios - Swift 3 中的标签栏按钮颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39401648/