使用swift Xcode 6的默认标签栏项目颜色

Nic*_*rmi 18 xcode ios swift xcode6

环境: - Xcode 6 beta 4 - Swift语言 - iOS标签应用程序(默认xCode项目)

如何将标签的默认灰色更改为其他内容?(最好是全球)

就我的研究而言,我需要以某种方式将每个标签的图像渲染模式更改为原始渲染模式,但我不知道如何

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

  • @Keenle:这会改变普通图像的颜色.那么选择的图像呢? (6认同)
  • 我创建了选项卡式应用程序,没有TabBarController(文件)类.我对这个"超级"IDE很生气...... (2认同)

pul*_*ulp 5

我没有足够的声誉来评论评论,但很多人都对如何更改所选图像的颜色感兴趣

之后再添加一个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)

希望有所帮助!