Search code examples
iosswiftuitabbarcontroller

I can't change the text of tab bar controller 8 items (after More button) using Swift


I added a tab bar controller of 8 items, but the system adds the 'more' button for me. The problem is I can't change the title of tab bar item 5 and 'more'. Here is the error message. I have confirmed that I have 8 Items.

Code :

tabBarController?.tabBar.items![5].title = "ok"

Error

Thread 1: Exception: "*** __boundsFail: index 5 beyond bounds [0 .. 4]"

Solution

  • Consider the following code:

    class TabBarController: UITabBarController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            configureViewControllers()
        }
    
        private func configureViewControllers() {
            let colors: [UIColor] = [.systemRed, .systemBlue, .systemGray, .systemTeal, .systemPink]
            var vcs = [UIViewController]()
            for i in 0...6 {
                let vc = UIViewController()
                vc.view.backgroundColor = colors.randomElement()!
                vc.tabBarItem.title = "VC \(i)"
                vcs.append(vc)
            }
            viewControllers = vcs
        }
    }
    

    So you have to set the titles of the view controllers via vc.tabBarItem.title = "your title" or you can set them even inside of your view controllers viewDidLoad() with tabBarItem.title = "...". For further reading: https://developer.apple.com/documentation/uikit/uitabbarcontroller