How to change default grey color of tab bar items?

筅森魡賤 提交于 2019-12-22 10:53:43

问题


I tried to change default grey color of Tab Bar items, but Xcode finds error. I used some code, that code is:

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))

}

So I put this in SecondViewController just as test, and when I run application on Xcode Simulator it crash and it show error in logs (console) fatal error: unexpectedly found nil while unwrapping an Optional value

I think problem is here:

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

Because when I delete this part of code, error doesn't happen. Can someone help me ?


回答1:


The problem in your code that you create UITabBar object like let tabBar = UITabBar() and this object has no relation to the tabs which are located on the form. Your tabBar is a new empty object that contains no one UITabBarItem objects and when you call this:

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

the error occurs when you try to do this: tabBar.items!.count. You're trying to unwrap optional items array [UITabBarItem]? and it nil becouse tabBar is empty object and have no items.

To fix this you need to get reference to UITabBar from current UITabBarController for example like this:

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.
    }
}


来源:https://stackoverflow.com/questions/33586620/how-to-change-default-grey-color-of-tab-bar-items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!