Search code examples
iosswiftuitabbarcontroller

Is there a way to change Tabbar images and action from embedded ViewController?


I have 5 ViewController that embedded with TabbarController. I created a class Tabbar to customize my Tabbar like :

class Tabbar: UITabBarController,UITabBarControllerDelegate {

var tabBarIteam = UITabBarItem()

@IBOutlet weak var tabbar: UITabBar!

 override func viewDidLoad() {

     super.viewDidLoad()
                        // THIS IS FOR FİRST TABBAR ITEM
   let selectedImage1 = UIImage(named: "vitrin_active")?.withRenderingMode(.alwaysOriginal)
    let deSelectedImage1 = UIImage(named: "vitrin_deactive")
           tabBarIteam = self.tabBar.items![0]
           tabBarIteam.image = deSelectedImage1
           tabBarIteam.selectedImage = selectedImage1

  .... I HAVE ALSO 4 MORE.
}

In my firstViewController , There is a button action

    @IBAction func ChangeTabbarimageAndAction(_ sender: Any) {
    ..
}

I want to change Tabbar images and actions (like push) when FirstView's ChangeTabbarimageAndAction tapped. Is this possible? If yes, How could I do? I searched in SO but can't find any solutions.


Solution

  • You can change action in delegate method of tabbar

     class yourclass: UIViewController, UITabBarDelegate {
            func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {
                print("push or present action")
            }
        }
    

    And for setting the image you can use

     let firstViewController:UIViewController = UIViewController()
            // The following statement is what you need
            let customTabBarItem:UITabBarItem = UITabBarItem(title: nil, image: UIImage(named: "YOUR_IMAGE_NAME"), selectedImage: UIImage(named: "YOUR_IMAGE_NAME"))
    
            firstViewController.tabBarItem = customTabBarItem