UIKit集成SwiftUI:如何设置导航栏标题不影响TabBar标题
Great question! I've run into this exact issue when mixing SwiftUI and UIKit tab bars too. The root problem here is that SwiftUI's navigation title modifiers end up setting the underlying UIHostingController's title property—and in UIKit, if you don't explicitly set a tabBarItem.title, the tab bar will default to using the view controller's title. That's why both your UIKit navigationItem.title setup and SwiftUI's .navigationBarTitle are messing with the tab bar text.
Here are two solid fixes tailored to your scenario:
Fix 1: Explicitly set the Tab Bar Item's title (simplest for your case)
Since your tab bar only shows icons anyway, just hardcode an empty string for the tab bar item's title directly on the UIHostingController. This decouples the tab bar text from the view controller's title entirely:
private let settingsViewController: UIViewController = { let hostingVC = UIHostingController(rootView: SettingsView()) // Lock the tab bar item to an empty title (matches your icon-only setup) hostingVC.tabBarItem.title = "" // Set the default navigation bar title for the root SettingsView hostingVC.navigationItem.title = "Settings" return hostingVC }()
Now, when you use .navigationBarTitle (or .navigationTitle for iOS 14+) in your SwiftUI nested views, it will update the navigation bar title without touching the tab bar item—because the tab bar is using its own explicitly set title instead of inheriting from the view controller's title.
Fix 2: Full SwiftUI navigation control (with UIKit guardrail)
If you want to handle all title logic within SwiftUI, wrap your SettingsView in a NavigationStack (iOS 16+) or NavigationView (older versions), and use .navigationTitle for each screen. You still need the UIKit tab bar lock from Fix 1, but this gives you full control over navigation titles inside SwiftUI:
// SwiftUI SettingsView struct SettingsView: View { var body: some View { NavigationStack { // Use NavigationView for iOS <16 List { NavigationLink("Nested Page") { NestedSettingsView() } } .navigationTitle("Settings") // Root navigation bar title } } } // SwiftUI Nested View struct NestedSettingsView: View { var body: some View { Text("This is a nested page") .navigationTitle("Nested Settings") // Only updates the navigation bar } }
Why this works
In UIKit, the tab bar item's title property takes absolute precedence over the view controller's title. By setting tabBarItem.title explicitly, you break the automatic link between the navigation bar title (controlled by either UIKit's navigationItem.title or SwiftUI's modifiers) and the tab bar text—just like how you used navigationItem.title instead of the view controller's title in pure UIKit.
内容的提问来源于stack exchange,提问作者Janosch Hübner

