Kee*_*nle 55
每个(默认)标签栏项目包含文本和图标.通过指定外观可以很容易地全局更改文本颜色:
// you can add this code to you AppDelegate application:didFinishLaunchingWithOptions:
// or add it to viewDidLoad method of your TabBarController class
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.magentaColor()], forState:.Normal)
UITabBarItem.appearance().setTitleTextAttributes([NSForegroundColorAttributeName: UIColor.redColor()], forState:.Selected)
Run Code Online (Sandbox Code Playgroud)
随着图像情况有点复杂.您无法全局定义其外观.您应该在TabBarController类中重新定义它们.在下面的viewDidLoad方法中添加代码TabBarController:
for item in self.tabBar.items as [UITabBarItem] {
if let image = item.image {
item.image = image.imageWithColor(UIColor.yellowColor()).imageWithRenderingMode(.AlwaysOriginal)
}
}
Run Code Online (Sandbox Code Playgroud)
我们知道imageWithColor(...)UIImage类中没有方法.所以这是扩展实现:
// Add anywhere in your app
extension UIImage {
func imageWithColor(tintColor: UIColor) -> UIImage {
UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
let context = UIGraphicsGetCurrentContext() as CGContextRef
CGContextTranslateCTM(context, 0, self.size.height)
CGContextScaleCTM(context, 1.0, -1.0);
CGContextSetBlendMode(context, .Normal)
let rect = CGRectMake(0, 0, self.size.width, self.size.height) as CGRect
CGContextClipToMask(context, rect, self.CGImage)
tintColor.setFill()
CGContextFillRect(context, rect)
let newImage = UIGraphicsGetImageFromCurrentImageContext() as UIImage
UIGraphicsEndImageContext()
return newImage
}
}
Run Code Online (Sandbox Code Playgroud)
imageWithColor借用了这个答案:https://stackoverflow.com/a/24545102/3050466
我没有足够的声誉来评论评论,但很多人都对如何更改所选图像的颜色感兴趣
之后再添加一个if let检查
if let image = item.image
Run Code Online (Sandbox Code Playgroud)
像这样:
if let selectedImage = item.selectedImage {
item.selectedImage = selectedImage.imageWithColor(UIColor.yellowColor()).imageWithRenderingMode(.AlwaysOriginal)
}
Run Code Online (Sandbox Code Playgroud)
这完全解决了这个问题.还有一点,因为你需要Swift 1.2和Xcode 6.3.2
for item in self.tabBar.items as! [UITabBarItem]
Run Code Online (Sandbox Code Playgroud)
代替
for item in self.tabBar.items as [UITabBarItem]
Run Code Online (Sandbox Code Playgroud)
希望有所帮助!
| 归档时间: |
|
| 查看次数: |
23499 次 |
| 最近记录: |