TabBar更改所选背景色

时间:2018-12-17 12:29:28

标签: ios swift tabbar

选中后,我将背景颜色更改为标签栏,但是在iPhone X中这是行不通的。

屏幕截图

Screen Shot

我的代码:

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!
    }
}

如何用自动高度更改选定的背景颜色?

任何帮助,谢谢!

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码更改选定的TabBar背景颜色。

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:当然,您应该将numberOfItems更改为所需的数字。

答案 1 :(得分:0)

尝试使用此代码

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