0
votes

I want to insert a new tab which is a SwiftUI view by UIHostingController into UITabBarController, Like this image:

enter image description here

The view is very simple,

ContentView.swift

struct ContentView: View {
       var body: some View {
            ZStack {
                Color(.red).opacity(0.2).edgesIgnoringSafeArea(.all)
                NavigationView {
                    Text("Hello")
                }
            }
}
    

And in AppDelegate.swift (disabled Scene) I get the viewControllers and insert like this:

let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "TabBarController") as! UITabBarController
let view = ContentView()
let viewController = UIHostingController(rootView: view)
controller.viewControllers?.insert(viewController, at: 0)
let item = controller.tabBar.items![0]
item.title = "Tab"
window.rootViewController = controller
self.window = window
window.makeKeyAndVisible()

The result is like above image, which is OK. But when I put the Text into NavigationView like:

var body: some View {
        ZStack {
            Color(.red).opacity(0.2).edgesIgnoringSafeArea(.all)
            NavigationView {
                Text("Hello")
            }
        }
}

Then the result is:

enter image description here

There's a gray blank bar which look equal to the tabbar there, how to remove it?

I have tried hide the tab bar by:

tabBarController.tabBar.isHidden = true

yes, it's gone, but I don't want to hide the tabBar. Any help, thanks!

2
Does this answer your question stackoverflow.com/a/64122705/12299030?Asperi
@Asperi Just tried it's hidden the tabBar same as tabBarController.tabBar.isHidden = true.William Hu

2 Answers

0
votes

I finally solved by deleting the UITabBarController in storyboard and re-added it. The old one was added by older Xcode version. I compared both UITabBarControllers, didn't see the difference in the interface builder.

0
votes

Just set the translucency of your TabBar to true.

In Storyboard:

Set the checkmark TabBar -> Style -> Translucent

Or in code

tabBar.isTranslucent = true