简体   繁体   中英

TabBar change selected background color

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

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!

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
}

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM