如何更改选项卡栏项目的默认灰色?

How to change default grey color of tab bar items?

我尝试更改 Tab Bar 项的默认灰色,但 Xcode 发现错误。我使用了一些代码,该代码是:

import UIKit

extension UIImage {
func makeImageWithColorAndSize(color: UIColor, size: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(size, false, 0)
    color.setFill()
    UIRectFill(CGRectMake(0, 0, size.width, size.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
  }
}

class SecondViewController: UIViewController {

let tabBar = UITabBar()

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.



    UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))

}

所以我把它放在 SecondViewController 中作为测试,当我 运行 在 Xcode 模拟器上应用程序时它崩溃并在日志中显示错误(控制台)致命错误:在展开可选值时意外发现 nil

我认为问题出在这里:

    UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))

因为当我删除这部分代码时,错误并没有发生。 有人可以帮助我吗?

您创建 UITabBar 对象(如 let tabBar = UITabBar())的代码存在问题,并且此对象与位于表单上的选项卡无关。您的 tabBar 是一个新的空对象,不包含任何 UITabBarItem 个对象,当您调用它时:

UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar.frame.width/CGFloat(tabBar.items!.count), tabBar.frame.height))

当您尝试这样做时出现错误:tabBar.items!.count。您正在尝试解包可选 items 数组 [UITabBarItem]? 并且它 nil 因为 tabBar 是空对象并且没有项目。

要解决此问题,您需要从当前 UITabBarController 获取对 UITabBar 的引用,例如:

class SecondViewController: UIViewController {

    var tabBar: UITabBar?

    override func viewDidLoad() {
        super.viewDidLoad()

        tabBar = self.tabBarController!.tabBar
        tabBar!.selectionIndicatorImage = UIImage().makeImageWithColorAndSize(UIColor.blueColor(), size: CGSizeMake(tabBar!.frame.width/CGFloat(tabBar!.items!.count), tabBar!.frame.height))
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}