4

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 ?

Emm
  • 1,963
  • 2
  • 20
  • 51

1 Answers1

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.
    }
}
Alexey Pichukov
  • 3,377
  • 2
  • 19
  • 22