UITabBarItem's title does not shown when using with Navigation controller

Viewed 1608

I'm having a trouble with my very simple app.

My app simply have 2 mains UIViewControllers called News and Category, each of them has their own UINavigationController.

So in AppDelegate.swift, I've done like this

window = UIWindow(frame: UIScreen.main.bounds)
let tabBarController = UITabBarController()

let newsVC = NewsVC()

// CREATE TAB BAR ITEM WITH TITLE ONLY
let newsVCTabBarItem = UITabBarItem(title: "News", image: nil, tag: 1)
newsVC.tabBarItem = newsVCTabBarItem

let categoryVC = CategoryVC()

// CREATE TAB BAR ITEM WITH TITLE ONLY
let categoryVCTabBarItem = UITabBarItem(title: "Category", image: nil, tag: 2)
categoryVC.tabBarItem = categoryVCTabBarItem

let rootViewControllers = [newsVC, categoryVC]

// CREATE NAVIGATION CONTROLLER FOR EACH OF THEM
tabBarController.viewControllers = rootViewControllers.map {
    UINavigationController(rootViewController: $0)
}
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()

When I run this simple application, the tab bar items do not show anything :(

But when I change the UITabBarItem to system's styles like this

let newsVCTabBarItem = UITabBarItem(tabBarSystemItem: .featured, tag: 1)

It's working perfectly! So hard to understand!

So does anyone know why my title-only tab bar item does not working? Have I missed something important?

Thanks in advance!

1 Answers

Add title property to the ViewControllers to show the title in UITabBarItem.

var title: String? { get set }

Set the title to a human-readable string that describes the view. If the view controller has a valid navigation item or tab-bar item, assigning a value to this property updates the title text of those objects.

let newsVC = ViewController()
newsVC.title = "News"

.....

let categoryVC = ViewController2()
categoryVC.title = "Category"

.....

Or

Assign an image to the UITabBarItem to see the result.

let newsVCTabBarItem = UITabBarItem(title: "News", image: UIImage(named: "news.png"), tag: 1)

....

let categoryVCTabBarItem = UITabBarItem(title: "Category", image: UIImage(named: "category.png"), tag: 2)

.....

Update:

Tab bar items are configured through their corresponding view controller. To associate a tab bar item with a view controller, create a new instance of the UITabBarItem class, configure it appropriately for the view controller, and assign it to the view controller’s tabBarItem property. If you don't provide a custom tab bar item for your view controller, the view controller creates a default item containing no image and the text from the view controller’s title property.

Related