'Can you replace a navigationItem.titleView using UIHostingController

I have a UINavigationController where I'd like to customise the navigationBar but I UIKit knowledge is limited to what I want. I do know SwiftUI so I thought I'd add a childView (a SwiftUI View)

import SwiftUI

struct NavView: View {
  [..]
 // I believe the content is not important to show here
}

I want to use that NavView inside the UINavigation:

import UIKit

class MyNavigationController: UINavigationController, UITabBarDelegate {
    
    // SwiftUI View
    var childView = UIHostingController(rootView: NavView())


    // Inside viewDidLoad
    let size = navigationBar.bounds.size
    let bounds = navigationBar.bounds
    childView.view.frame = .init(x: 6, y: 0, width: size.width - 12, height: bounds.height) // My requirements

    navigationBar.addSubview(childView.view)
    // Not sure I need this
    self.view.bringSubviewToFront(childView.view)

}

I can see my SwiftUI View but the title is above the view. I do not need the titleView. Could I remove it? Things tried:

self.navigationItem.titleView?.removeFromSuperview()
self.navigationItem.titleView = ""
self.navigationItem.titleView = UIView()

Whatever I do, this "hidden" view pushes my childView down; it's not centered.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source