Swift 5
Lets say you have a class that inherits UITabBarController
like below:
final class YourTabBarController: UITabBarController { .. }
Define 2 types of attribute in this YourTabBarController
:
let normalTabBarAttributes: [NSAttributedString.Key: Any] = [
.font: NotSelectedFont,
.foregroundColor: NotSelectedColor
]
let selectedTabBarAttributes: [NSAttributedString.Key: Any] = [
.font: SelectedFont,
.foregroundColor: SelectedColor
]
And you have a ViewController
named YourViewController
that contains the TabBar
and inherits UIViewController
like below:
final class YourViewController: UIViewController {...}
iOS 15.0 or later version
Define a method in YourViewController
:
private func setTabBarAttributes() {
guard let yourTabBarController = tabBarController as? YourTabBarController else {
return
}
let appearance = UITabBarAppearance()
appearance.stackedLayoutAppearance.normal.titleTextAttributes = yourTabBarController.normalTabBarAttributes
appearance.stackedLayoutAppearance.selected.titleTextAttributes = yourTabBarController.selectedTabBarAttributes
yourTabBarController.tabBar.standardAppearance = appearance
yourTabBarController.tabBar.scrollEdgeAppearance = appearance
}
Form override func viewDidLoad()
method of YourViewController
call that method:
setTabBarAttributes()
previous versions of iOS 15.0
In YourTabBarController
you can define a method :
private func updateTabBarAttributes() {
guard let viewControllers = viewControllers else { return }
for viewController in viewControllers {
if viewController == selectedViewController {
viewController.tabBarItem.setTitleTextAttributes(selectedTabBarAttributes, for: .normal)
} else {
viewController.tabBarItem.setTitleTextAttributes(normalTabBarAttributes, for: .normal)
}
}
}
Now use the method like below:
override var selectedIndex: Int {
didSet {
updateTabBarAttributes()
}
}
override var selectedViewController: UIViewController? {
didSet {
updateTabBarAttributes()
}
}