Oleh Liskovych
Oleh Liskovych

Reputation: 1061

How to customize appearance of a single tab bar item?

I need middle tab bar item to look different from others. Here is an illustration:

enter image description here

How can I achieve this?

EDIT: All tabs except of middle react on selection in standard way. Only middle tab looks the same when selected.

Upvotes: 0

Views: 836

Answers (2)

Jitendra Modi
Jitendra Modi

Reputation: 2394

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

Upvotes: 2

glyvox
glyvox

Reputation: 58139

You should subclass UITabBarController and change the appearance of the third UITabBarItem in its items array inside 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

            [...]
        }
    }
}

Upvotes: 0

Related Questions