To show a different screen in one tab depending on API data, for example an empty state when there are no purchases, build the tab bar's view controllers once and wrap that tab in a UINavigationController. When the data arrives, replace only that tab's screen with setViewControllers(_:animated:). Assigning a new viewControllers array every time, as the 2018 code did in viewWillAppear, swaps out all five tabs and throws away whatever the user had open in them.
SWIFT TIPS · UIKIT · UITABBARCONTROLLER
First posted on June 10, 2018 for Swift 4, as "Swift 4 Change viewController In Tab Bar Controller With data IF, Else (API)". Rewritten on November 18, 2026. The tab bar tests were run on a Mac as a Mac Catalyst program, which runs UIKit on macOS (not an iPhone or the simulator), with Swift 6.2.3 (Xcode 26.2) on macOS 26.0.1, using a stub in place of the network. The code was type-checked against the iOS 26.2 SDK in Swift 5 and Swift 6 modes with iOS 15 and iOS 26.2 as deployment targets, but not run on a device.
The app in the 2018 post had five tabs: Beranda, Profil, Pembelian, Klaim and Pengaturan. The Pembelian (purchases) tab had to show the list of purchases, or an empty screen when the user hadn't bought anything. The post's tab bar controller called the API in viewWillAppear and, in each branch of an if, created all five view controllers, set their titles and icons, and assigned them to viewControllers. The two branches differed by one line.
The idea, picking a screen from the data, is right. The way it was applied replaces more than it needs to, and it runs more often than it needs to.
What reassigning all five tabs does
I made a tab bar controller with the same five tabs, opened the Profil tab, pushed an "Edit profile" screen on it, and then did what the 2018 code did when data arrived: assigned five new view controllers. Then I did the same with the new approach, which replaces only the purchases tab's screen:
2018 approach
before reload: selected tab 1, its stack ["Profil", "Edit profile"]
after reload: selected tab 1, its stack ["Profil"], same object as before: false
New approach
before: selected tab 1, its stack ["Profil", "Edit profile"]
after: selected tab 1, its stack ["Profil", "Edit profile"], purchases tab shows ["Pembelian kosong"], same tab bar item: true
After the reassignment, the selected tab was still number 1, but it was a new Profil screen, and the "Edit profile" screen the user had open was gone. Apple's documentation for viewControllers explains why: the tab bar controller removes all the old view controllers, tries to reselect the previously selected object, and if that object is gone, selects the one at the same index. New objects are never "the same", so every tab starts over.
In my test each tab sits in a navigation controller so the lost screen is easy to see. The 2018 tabs were plain view controllers, so there it was anything those screens held: scroll position, loaded data, a half-filled form.
Build the tabs once, swap one screen
import UIKit
protocol PurchaseService: Sendable {
func purchaseCount() async throws -> Int
}
final class HomeTabBarController: UITabBarController {
private let service: PurchaseService
private let purchasesNav = UINavigationController()
private var hasLoaded = false
init(service: PurchaseService) {
self.service = service
super.init(nibName: nil, bundle: nil)
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
// Build the five tabs once. Each tab is a navigation controller, so its tab bar item
// stays put while the screen inside it changes.
purchasesNav.setViewControllers([LoadingViewController()], animated: false)
viewControllers = [
tab(HomeViewController(), title: "Beranda", symbol: "house"),
tab(ProfileViewController(), title: "Profil", symbol: "person"),
tab(purchasesNav, title: "Pembelian", symbol: "bag"),
tab(ClaimsViewController(), title: "Klaim", symbol: "doc.text"),
tab(SettingsViewController(), title: "Pengaturan", symbol: "gearshape"),
]
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
guard !hasLoaded else { return } // viewWillAppear can run many times; load once
hasLoaded = true
refreshPurchases()
}
/// Call again after a purchase, a pull to refresh, or a push notification.
func refreshPurchases() {
Task { [weak self] in
guard let self else { return }
let screen: UIViewController
do {
let count = try await service.purchaseCount()
screen = count == 0 ? EmptyPurchasesViewController() : PurchasesViewController()
} catch {
let retry = RetryViewController()
retry.onRetry = { [weak self] in self?.refreshPurchases() }
screen = retry
}
purchasesNav.setViewControllers([screen], animated: false)
}
}
private func tab(_ controller: UIViewController, title: String, symbol: String) -> UIViewController {
let nav = controller as? UINavigationController ?? UINavigationController(rootViewController: controller)
nav.tabBarItem = UITabBarItem(title: title, image: UIImage(systemName: symbol), tag: 0)
return nav
}
}
// Placeholders for the app's own screens.
final class HomeViewController: UIViewController {}
final class ProfileViewController: UIViewController {}
final class ClaimsViewController: UIViewController {}
final class SettingsViewController: UIViewController {}
final class LoadingViewController: UIViewController {}
final class PurchasesViewController: UIViewController {}
final class EmptyPurchasesViewController: UIViewController {}
final class RetryViewController: UIViewController { var onRetry: (() -> Void)? }
With a stub service in place of the API, I ran the tab bar controller for three answers, and made it appear a second time after the first load:
0 purchases: tabs ["Beranda", "Profil", "Pembelian", "Klaim", "Pengaturan"], purchases tab shows EmptyPurchasesViewController, profile tab kept after a second appearance: true
3 purchases: tabs ["Beranda", "Profil", "Pembelian", "Klaim", "Pengaturan"], purchases tab shows PurchasesViewController, profile tab kept after a second appearance: true
network error: tabs ["Beranda", "Profil", "Pembelian", "Klaim", "Pengaturan"], purchases tab shows RetryViewController, profile tab kept after a second appearance: true
How it works
- The tabs are built in
viewDidLoad. That runs once per tab bar controller, so the five tabs and their items are created once. - The purchases tab is a navigation controller you keep.
purchasesNavstays in the tab bar the whole time. Only its root screen changes, so its tab bar item, title and icon don't move or flicker. - The data loads once.
viewWillAppearcan run many times, every time the tab bar controller's view is about to appear again. ThehasLoadedflag keeps it to one request, andrefreshPurchases()is there for the moments you know the data changed, such as after a purchase. - Errors get their own screen. A failed request shows a retry screen instead of the empty state, so "no purchases" and "no connection" don't look the same.
- The service is a protocol.
PurchaseServicehas one async method, which is what made the stub test above possible. The 2018 code calledNetworkServicedirectly, withonFailure: nil, so a failed request did nothing. - SF Symbols for icons.
UIImage(systemName:)replaces the five PNG files, and the symbols take the tab bar's selected and unselected colors.
Other small things in the 2018 code
DispatchQueue.main.asyncaround the request.viewWillAppearalready runs on the main thread, so wrapping the call in a main-queue block only delayed it slightly.super.viewWillAppear(true). The override should pass on its ownanimatedvalue instead of alwaystrue.- A count of zero against
nil.self.dataBeli?.data?.count == 0is false whendataisnil, so a missing list fell into the "has purchases" branch. Checking(data ?? []).isEmptytreats both the same.
A quick check for your project
- Search for
viewControllers = [outside of setup code. If it runs after the app is showing, users lose their place in every tab. - Search for network calls in
viewWillAppearand count how often they really need to run. - Turn on airplane mode and open each data-driven tab. An empty state should never be the answer to a failed request.
What the 2018 version said
The original included two screenshots from the app, with the app's title area covered. The first shows the purchases tab with purchases, a list of colored cards. The second shows the empty state, a sad shopping bag:


Keep reading on JR Devhub
Comments