如何自定义单个标签栏项的外观?

时间:2017-09-04 09:14:21

标签: ios swift uitabbarcontroller

我需要中间标签栏项目看起来与其他项目不同。这是一个例子:

enter image description here

我怎样才能做到这一点?

编辑: 除中间的所有选项卡都以标准方式对选择作出反应。选中时,只有中间选项卡看起来相同。

2 个答案:

答案 0 :(得分:1)

Take a subclass of TabbarController.Remember to call  `<UITabBarControllerDelegate>`


    func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //
        tabBar.selectionIndicatorImage = returnImageofSelectetab()
    }

//Method called everytime when you select tab.

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {

        if tabBarController.tabBar.selectionIndicatorImage == nil {
            print("Starting point delegate: Selection indicator image is nill")
        }
        else {
            print("Starting Point Of delegate: Selection indicator image is available")
        }

//HERE i gave index where I want to set image.
        if tabBarController.selectedIndex == 2 {
            tabBarController.tabBar.selectionIndicatorImage = nil
        }
        else {
            tabBarController.tabBar.selectionIndicatorImage = returnImageofSelectetab()
        }
        if tabBarController.tabBar.selectionIndicatorImage == nil {
            print("Ending point delegate: Selection indicator image is nill")
        }
        else {
            print("Ending Point Of delegate: Selection indicator image is available")
        }
    }

        func returnImageofSelectetab() -> UIImage {
        //HERE 'img_sel' is YOUR SELECTED IMAGE SET AS BACKGROUND OF YOUR TABBARITEM
            let selTab = UIImage(named: "img_sel")?.withRenderingMode(.alwaysOriginal)
            let tabSize = CGSize(width: view.frame.width / 5, height: 49)
            UIGraphicsBeginImageContext(tabSize)
            selTab?.draw(in: CGRect(x: 0, y: 0, width: tabSize.width, height: tabSize.height))
            let reSizeImage: UIImage? = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            return reSizeImage!
        }

答案 1 :(得分:0)

您应该继承UITabBarController并更改UITabBarItemitems数组中第三个awakeFromNib的外观。

class CustomTabBarController: UITabBarController {
    override func awakeFromNib() {
        super.awakeFromNib()

        guard let items = tabBar.items else {
            return
        }

        for i in 0 ..< items.count {
            item.image = image
            item.selectedImage = selectedImage

            [...]
        }
    }
}