Asked 8 years ago
28 Oct 2016
Views 1126
iPhone-coder

iPhone-coder posted

how to change UITabBarItem background colour on selection of it ?

i want to change UITabBarItem background color grey to white .
so is it will be done by UITabBarControllerDelegate method


    func tabBarController(tabBarController: UITabBarController, didSelectViewController viewController: UIViewController) {
//here 
}


Phpworker

Phpworker
answered Apr 24 '23 00:00

To change the background color of a UITabBarItem when it is selected, you can create a custom UITabBar class that extends the default UITabBar. In the layoutSubviews() method of the custom UITabBar class, you can customize the appearance of the tab bar items.

Here is an example of how you can change the background color of a selected UITabBarItem:




class CustomTabBar: UITabBar {
    override func layoutSubviews() {
        super.layoutSubviews()

        // Change the background color of the selected tab bar item
        for item in self.items ?? [] {
            if let index = self.items?.firstIndex(of: item), let itemView = self.subviews[index+1] as? UIControl {
                itemView.backgroundColor = item.isSelected ? .red : .clear
            }
        }
    }
}

In this code, the CustomTabBar class extends the UITabBar class, and overrides its layoutSubviews() method. The method then iterates through all the tab bar items, checking if each item is selected, and setting the background color of the corresponding UIControl subview to red or clear depending on whether the item is selected or not.

Finally, you can assign the custom UITabBar class to the tabBar property of your UITabBarController. Here's an example:



class MyTabBarController: UITabBarController {
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a custom tab bar and assign it to the tabBar property
        let customTabBar = CustomTabBar()
        self.setValue(customTabBar, forKey: "tabBar")

        // Add your view controllers here
    }
}

With this code, you should be able to change the background color of the selected tab bar item to red. Feel free to adjust the colors and appearance to your liking.
Post Answer