簡體   English   中英

TabBar更改所選背景色

[英]TabBar change selected background color

選中后,我將背景顏色更改為標簽欄,但是在iPhone X中這是行不通的。

屏幕截圖

屏幕截圖

我的代碼:

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

如何用自動高度更改選定的背景顏色?

任何幫助,謝謝!

您可以使用以下代碼更改選定的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
}

PS:當然,您應該將numberOfItems更改為所需的數字。

試試這個代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM