标签栏按钮颜色在Swift 3?

时间:2016-09-08 23:34:02

标签: ios swift storyboard uitabbarcontroller swift3

在Swift 2中,我在Storyboard中使用了用户定义的运行时属性,并使用了tintColor的关键路径来更改标签栏项目图标的颜色。但是,看起来tintColor被Swift 3删除了。如何更改Swift 3中标签栏控制器中标签栏项目的选定颜色?

谢谢!

编辑:附上截图

enter image description here

2 个答案:

答案 0 :(得分:11)

使用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())

答案 1 :(得分:0)

与Swift 3相同的最新代码是

extension UIImage {

    func tabBarImageWithCustomTint(tintColor: UIColor) -> UIImage {

        UIGraphicsBeginImageContextWithOptions(self.size, false, self.scale)
        let context: CGContext = UIGraphicsGetCurrentContext()!

        context.translateBy(x: 0, y: self.size.height)
        context.scaleBy(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.clip(to: rect, mask: self.cgImage!)

        tintColor.setFill()
        context.fill(rect)

        var newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        newImage = newImage.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
        return newImage
    }
}