How to change the default gray color of tab bar items?

I tried to change the gray color of the default elements Tab Bar, but Xcode detected an error. I used some code, this code:

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 SecondViewControllerexactly the same way as the test, and when I run the application on Xcode Simulator, it crashes and it shows an error in logs (console) fatal error: nil was unexpectedly found when deploying an optional value

I think the 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 the code, no error occurs. Can anybody help me?

+2
source share
1 answer

, 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 becouse tabBar - .

, UITabBar UITabBarController, , :

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

Source: https://habr.com/ru/post/1614856/


All Articles