TabBar选择项目更改背景颜色

时间:2018-05-14 13:35:41

标签: ios swift tabbar

当用户点击标签栏项目时,我尝试更改背景颜色。我的代码:

//MARK: func
func settingTabBar(){
    //настроили бэкгроунд активного таб бара на зеленный цвет
    let numberOfItems = CGFloat((tabBarController?.tabBar.items!.count)!)
    let tabBarItemSize = CGSize(width: (tabBarController?.tabBar.frame.width)! / numberOfItems, height: (tabBarController?.tabBar.frame.height)!)
    tabBarController?.tabBar.selectionIndicatorImage = UIImage.imageWithColor(color: Helpers.followGreenColor, size: tabBarItemSize).resizableImage(withCapInsets: .zero)

    // remove default border
    tabBarController?.tabBar.frame.size.width = self.view.frame.width + 4
    tabBarController?.tabBar.frame.origin.x = -2
}

选择项目颜色更改但不完全。看下面的屏幕。 THX。

my screen

my problem

upd:

screen view hierarchy

1 个答案:

答案 0 :(得分:0)

我用以下代码解决了这个问题

class ChildTabBarController: UITabBarController {

        override func viewDidLoad() {
            super.viewDidLoad()

            changeBckgColorSelection()
        }

        fileprivate func changeBckgColorSelection() {
                let imgSize = CGSize(width: tabBar.frame.size.width / CGFloat(tabBar.items!.count),
                                     height: tabBar.frame.size.height)
                UIGraphicsBeginImageContextWithOptions(imgSize, false, 0)
                let p = UIBezierPath(rect: CGRect(x: 0, y: 0, width: imgSize.width,
                                                  height: imgSize.height))
                Helpers.followGreenColor.setFill()
                p.fill()
                let finalImg = UIGraphicsGetImageFromCurrentImageContext()
                UIGraphicsEndImageContext()
                self.tabBar.selectionIndicatorImage = finalImg
            }
    }