SwiftUI - Unable to set title on UIKit's NavigationController

63 Views Asked by At

I am working for a corporate and we have our own set of customised UIKit elements adapting to our brand guide which could be integrated using Cocoapods. I am just starting my first SwiftUI project and struggling to make use of our components from CorporateKit since they are built for UIKit.

We use the NavigationController from CorporateKit in UIKit project as below. NavigationController is created by just passing the UIViewController as input and it is set as rootViewController in SceneDelegate.

let navigationController = CorporateNavigationController(rootViewController: home)
self.window?.rootViewController = navigationController

But, I couldn't able to use it directly in SwiftUI project. I went through "Interfacing with UIKit" topic and tried to implement the same for CorporateNavigationController.

import SwiftUI
import CorporateKit

struct CorporateNavigationStack: UIViewControllerRepresentable {
    
    func makeUIViewController(context: Context) -> CorporateKit.CorporateNavigationController {
        return CorporateNavigationController(rootViewController: UIViewController())
    }
    
    func updateUIViewController(_ uiViewController: CorporateKit.CorporateNavigationController, context: Context) {
        
    }
}

#Preview {
    CorporateNavigationStack()
}

And in the ContentView,

import SwiftUI

struct ContentView: View {
    var body: some View {
        CorporateNavigationStack()
            .navigationTitle("Title")
    }
}

#Preview {
    ContentView()
}

I am trying to set title to the NavigationController and it is not set. I am not sure about what I miss here!

1

There are 1 best solutions below

0
vrwim On

UINavigationController (which I assume your CorporateNavigationController is a sublass of) finds its title from the title property of the UIViewController it's currently displaying.

So to get a title showing, you will need to set the title property like so:

func makeUIViewController(context: Context) -> CorporateKit.CorporateNavigationController {
    let viewController = UIViewController()
    viewController.title = "This is the title"
    return CorporateNavigationController(rootViewController: viewController)
}

The .navigationTitle modifier only works on SwiftUI NavigationStack or NavigationView. I would suggest using either UIKit (or CorporateKit in your case) or SwiftUI, and only mixing them when needed. That is, when using SwiftUI in an app and you can't make it in SwiftUI, leveraging UIViewControllerRepresentable to make a part in UIKit.