ios - Swift 3 中的标签栏按钮颜色?

标签 ios swift storyboard uitabbarcontroller swift3

在 Swift 2 中,我在 Storyboard 中使用了一个用户定义的运行时属性,其关键路径为 tintColor 来更改选项卡栏项目图标的颜色。但是,似乎 tintColor 已随 Swift 3 一起删除。如何在 Swift 3 的选项卡栏 Controller 中更改选项卡栏项目的选定颜色?

谢谢!

编辑:附截图

enter image description here

最佳答案

使用 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/

相关文章:

swift - 拍照允许我在 BSImagePicker Swift ios 中选择超过 maxNumberOfSelections

ios - 如何清除/删除iOS上的键盘缓存?

ios - 在以编程方式更改文本属性后,在 iOS 7 的 IB 中配置的 textView 将字体更改回默认字体

iOS后退按钮行为: double back

ios - 一旦在 Swift 中达到最大高度,UITextView 就会变得可滚动

objective-c - 如何在 Objective-C 中使用 Swift 结构

ios - 相互交换 Sprite 位置

ios - 添加 subview Controller 并更改其标签

objective-c - 始终可见的 UIView

ios - 如何检查我的应用程序是否通过 Siri 快捷方式恢复