iOS10、UIToolbar背景色不变

iOS 10, UIToolbar background color does not change

我有一个从 iOS 8 开始就存在的应用程序。它的工作方式是你有一个 UITableView 并点击单元格以产生一个分数,根据分数,底部的 UItoolbar 会改变颜色使用此方法:

func updateToolbarAndLabel(score: Int) {

    if(score <= -1) {
        self.toolbar.backgroundColor = UIColor.greenColor()
    } else if(score <= 0) {
        self.toolbar.backgroundColor = .None
    } else if(score <= 9) {
        self.toolbar.backgroundColor = UIColor.greenColor()
    } else if(score <= 29) {
       self.toolbar.backgroundColor = UIColor.yellowColor()
    } else if(score >= 30) {
        self.toolbar.backgroundColor = UIColor.redColor()
    }
    if (score <= 0) {
        self.scoreshow.text = "0"
    } else {
        self.scoreshow.text = (score as NSNumber).stringValue }
}

然后每次点击 table 视图时都会调用它:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

事情是,自从我构建应用程序以来它一直有效,但在 iOS 10 上,它不起作用。简单的说颜色不变...

任何帮助将不胜感激

我解决了,改成这样:BarTintColor,我自己发现在apple docs里找不到任何东西提到它

这样使用:self.toolbar.barTintColor

编辑:现在在 GM 发布文档中提到了它,请参阅下面的回答

我设法使用以下代码在 IOS 10 和 Swift 3 上完成这项工作:

let dummyToolbar = UIToolbar()
dummyToolbar.barTintColor = .lightGray
dummyToolbar.sizeToFit() // without this line it doesn't work

使用 barTintColor 不会产生我想要的正确颜色,但以下方法在 iOS 11 / Swift 4.

中对我有用

首先,创建一个任意大小的图像,它是您想要的栏的纯色。

之后,使用以下扩展名:

import UIKit

extension UIToolbar {
    func setBackgroundColor(image: UIImage) {
        setBackgroundImage(image, forToolbarPosition: .any, barMetrics: .default)
    }
}

您创建的纯色图像随后将用作工具栏的背景,并且应该与您想要的颜色完美匹配。

在此示例中,我使用了带有紫色的 1x1 图片:

对于 iOS 11 & 12 Swift 4 我可以用这个代码来完成:

self.navigationController?.toolbar.barTintColor = UIColor.init(white: 0.9, alpha: 1)

这在 xCode 11 中适用于 IOS12 和 Swift 4:

            self.navigationController?.toolbar.barTintColor = UIColor.black

更改背景颜色:

toolBar.barTintColor = UIColor.musalaDarkBlueColor

更改按钮颜色:

toolBar.tintColor = UIColor.white