How do I change background color of UITabItem when item is selected

前端 未结 11 1055
暖寄归人
暖寄归人 2021-02-01 19:15

I would like a different background color when the user selects a tab bar item than when it is unselected.

11条回答
  •  伪装坚强ぢ
    2021-02-01 19:40

    My answer is similar to @Mehul Thakkar but it is in Swift 4 and to improve on his answer I would say that if you place the code in viewDidAppear as he suggests users will see the change happening which is not good user experience.

    So create the custom class for your tabbar controller and in viewDidLoad place the following code:

    let singleTabWidth: CGFloat = self.tabBar.frame.size.width / CGFloat((self.tabBar.items?.count)!)
    let singleTabSize = CGSize(width:singleTabWidth , height: self.tabBar.frame.size.height)
    
    let selectedTabBackgroundImage: UIImage = self.imageWithColor(color: .white, size: singleTabSize)
    self.tabBar.selectionIndicatorImage = selectedTabBackgroundImage
    

    The imageWithColor function is below for you:

    //image with color and size
        func imageWithColor(color: UIColor, size: CGSize) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()
    
            context!.setFillColor(color.cgColor)
            context!.fill(rect)
    
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
    
            return image!
        }
    

    Hope this helps someone.

提交回复
热议问题