Home > Software engineering >  How to add a TabBarItem in specific index of UITabBarController?
How to add a TabBarItem in specific index of UITabBarController?

Time:01-03

How to add a TabBarItem in specific index of UITabBarController?

I can add a new tabbar item using,

[self.tabBarItems addObject:nav];

It always adds in the last. I need to add the tabbar item in a specific index position. How can I do so?

CodePudding user response:

Here a way to insert new view tab bar item :

import UIKit

class ViewController: UIViewController {
    
    // button and textfields are defined in the storyboard
    @IBOutlet var button: UIButton!
    var tabbar: UITabBarController?
    @IBOutlet var label: UITextField!
    @IBOutlet var image: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        label.text = "Four"
        image.text = "info.circle.fill"
        tabbar = self.tabBarController
    }

    @IBAction func addVC(button: UIButton) {
        // remove keyboard
        label.resignFirstResponder()
        image.resignFirstResponder()
        // check that everything is set
        if var tbVC = tabbar?.viewControllers,
           let title = label.text,
           let imageName = image.text {
            // create new view controller
            let newVC = UIViewController()
            
            // vreate the tab bar item for the new view controller
            let tabBarItem = UITabBarItem(title: title,
                                          image: UIImage(systemName: imageName),
                                          tag: tbVC.count   1)
            newVC.tabBarItem = tabBarItem
            
            // insert new tab in tab bar view controller
            tbVC.insert(newVC, at: 2)
            
            // update the teb bar controller
            tabbar?.setViewControllers(tbVC, animated: true)
        }
    }

}
  • Related