0

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?

Sazzad Hissain Khan
  • 37,929
  • 33
  • 189
  • 256
  • You can try her tab bar controller view controllers list, insert your view controller where you want then update tab bar controller view controller list and then set tab bar item for this new view controller. – Ptit Xav Jan 02 '22 at 09:00
  • @PtitXav could you please answer with sample code? – Sazzad Hissain Khan Jan 02 '22 at 09:47

1 Answers1

1

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

}
Ptit Xav
  • 3,006
  • 2
  • 6
  • 15