1

hi i want to change the unselected bur item color to white and i wrote this code :

for item in self.tabBar.items as [UITabBarItem]! {
        if let image = item.image {
            item.image = image.imageWithColor(UIColor.whiteColor()).imageWithRenderingMode(.AlwaysOriginal)
        }
    }

but i gives me this error in the first line :

fatal error: unexpectedly found nil while unwrapping an Optional value

what should i do?

Farzam
  • 177
  • 1
  • 13
  • Are you using a custom image as Tab Bar Item Icon or a System Image? – Ishan Handa Sep 22 '15 at 16:10
  • Please expand your question with more of your code. A simple iteration like "for item in self.tabBar.items! {}" works well in a standard UITabBarController if there are tabbar items – peacer212 Sep 22 '15 at 16:27
  • @Ishanhanda no i'm using custom images – Farzam Sep 22 '15 at 16:44
  • @peacer212 yes i know and it used to work but when i added local notification, it stopped working. i don't know why because these two are totally irrelevant. – Farzam Sep 22 '15 at 16:45
  • I can't really help you because I can't reproduce the error. Could you make a [GIST](https://gist.github.com/) with a more complete code example? – peacer212 Sep 22 '15 at 16:54
  • @peacer212 sure. but before that, is there any other way to make the tabBarItems white? – Farzam Sep 22 '15 at 16:56
  • Your approach works fine, I just tested it with the `getImageWithColor ` function of this [link](http://stackoverflow.com/questions/26542035/create-uiimage-with-solid-color-in-swift) – peacer212 Sep 22 '15 at 17:11

1 Answers1

0

Here is a minimum code example that works for me

class MyTabBarController : UITabBarController {

    override func viewDidLoad() {

        if let items = self.tabBar.items {
            for item : UITabBarItem in items {
                if let image = item.image {
                    item.image = getImageWithColor(UIColor.whiteColor(), size: image.size).imageWithRenderingMode(.AlwaysOriginal)
                }
            }
        }
    }

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

}

The getImageWithColor function is taken from this answer. In case you also want the selected tabs to be white squares, set the item.selectedImage property as well.

Community
  • 1
  • 1
peacer212
  • 935
  • 9
  • 15