I am pushing a UIViewController
that conforms to UIViewControllerRepresentable
on to the navigation stack from a SwiftUI View via NavigationLink
and I would like to set the title for the ViewController.
However, I am unable to and just get an empty title. I suspect this is a SwiftUI bug but was hoping that I am perhaps missing something.
Below are the lines I have tried that don't work.
title = "Title"
navigationItem.title = "Title"
Here is code to reproduce the issue
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
List {
NavigationLink {
ViewControllerRepresentable()
} label: {
Text("Go to ViewController")
}
}
.navigationTitle(Text("SwiftUI View"))
}
}
}
struct ViewControllerRepresentable: UIViewControllerRepresentable {
typealias UIViewControllerType = ViewController
func makeUIViewController(context: Context) -> ViewController {
ViewController()
}
func updateUIViewController(_ uiViewController: ViewController, context: Context) {
}
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = "title"
title = "title"
}
}
CodePudding user response:
Try setting the title in SwiftUI:
NavigationLink {
ViewControllerRepresentable()
.navigationTitle("My UIViewController")
} label: {
Text("Go to ViewController")
}
And then your can remove these lines from your view controller unless you intend to use it in UIKit as well (in which case just navigationItem.title
should be enough):
navigationItem.title = "title"
title = "title"