I have a SwiftUI NavigationView and a SwiftUI view displayed in SwiftUI. The navigation link refers to a UIViewControllerRepresentable wrapping a UIViewController. I have been unable to remove the back button title, nor have I been able to set the tint of the back button when navigating to this UIKit view controller. This is targeting iOS 15.
Here's a minimal application that attempts it. I had similar issue just setting the Title for the UIKit view controller, but found reference to the SwiftUI modifier on the NavigationLink. I haven't found other modifiers for tint nor removing back button title.
I've also seen references that this needs to be done after the view controller moves to a wrapper parent controller that SwiftUI creates during this process. I've tried putting it in viewWillAppear
, viewDidAppear
, init()
, didMove(toParent:
, willMove(toParent
. These work for setting the title but not for setting the tint nor removing back button text.
I've tried setting backButtonDisplayMode = .minimal
in a bunch of places with confusing results.
import SwiftUI
import UIKit
struct ContentView: View {
init() {
UIBarButtonItem.appearance().tintColor = .systemPink
}
var body: some View {
NavigationView {
VStack {
NavigationLink(destination: MyViewControllerRepresentable()
.navigationTitle("TitleFromSwiftUI")) {
Text("MyVC")
}
Spacer()
}
.navigationTitle("Top")
.navigationBarTitleDisplayMode(.inline)
}
}
}
struct MyViewControllerRepresentable: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> MyViewController {
return MyViewController()
}
func updateUIViewController(_ uiViewController: MyViewController, context: Context) {}
}
class MyViewController : UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
title = "Nested view" // Doesn't work when pushed from SwiftUI view
navigationItem.backButtonDisplayMode = .minimal // Only works for nested views
navigationItem.backBarButtonItem?.tintColor = .systemPink // Never works
let button = UIButton(primaryAction: UIAction { _ in
self.navigationController?.pushViewController(MyViewController(), animated: true)
})
button.frame = CGRect(x: 100, y: 150, width: 200, height: 20)
button.setTitle("Button", for: .normal)
view.addSubview(button)
}
}
#Preview {
ContentView()
}