0

I change background color into tab bar when selected, but in iPhone X this is doesn't work.

Screen Shot

Screen Shot

My code:

class TabbarVC: UITabBarController {

override func viewDidLoad() {
    super.viewDidLoad()

    let numberOfItems = CGFloat(tabBar.items!.count)
    UITabBar.appearance().selectionIndicatorImage = UIImage().makeImageWithColorAndSize(color: #colorLiteral(red: 0.1294117719, green: 0.2156862766, blue: 0.06666667014, alpha: 1), size: CGSize(width:tabBar.frame.width/numberOfItems,height:(tabBar.frame.height)))
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
    tabBar.invalidateIntrinsicContentSize()
    tabBar.superview?.setNeedsLayout()
    tabBar.superview?.layoutSubviews()
    }
 }

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

How change selected bckg color with automatic height?

Any help, thanks!

Sham Dhiman
  • 1,348
  • 1
  • 21
  • 59

2 Answers2

0

You can change selected TabBar background color with below code.

private func changeTabBarBackground(){
    //Change Background Color of Selected Image
    let numberOfItems = CGFloat(5)
    let tabBarItemSize = CGSize(width: (self.tabBar.frame.width) / numberOfItems,
                                height: (self.tabBar.frame.height))

    self.tabBar.selectionIndicatorImage
        = UIImage.imageWithColor(color: UIColor.green,
                                 size: tabBarItemSize).resizableImage(withCapInsets: .zero)

    self.tabBar.frame.size.width = (self.view.frame.width) + 4
    self.tabBar.frame.origin.x = -2
}

P.S: Of course you should change the numberOfItems to your desire number.

Emre Önder
  • 2,408
  • 2
  • 23
  • 73
0

Try this code

let numberOfItems = CGFloat(tabBar.items!.count)
let tabBarItemSize = CGSize(width: tabBar.frame.width / numberOfItems, height: tabBar.frame.height)
tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: UIColor.red, size: tabBarItemSize).resizableImage(withCapInsets: UIEdgeInsets.zero)
tabBar.frame.size.width = self.view.frame.width + 4
tabBar.frame.origin.x = -2