I'm trying to make a custom back button for the NavigationBar
where I can put whatever text I like. My primary use case is that some of my views have no title, and when I click to a new view from that, the new view's back button in the navigation bar has no text, and only an arrow. It makes it hard for the user to tap this. I'm looking to set a custom back button that has the text "Back", but also has the back button icon, and works flawlessly with SwiftUI's animation mechanism.
This is my current attempt to wrap a UIKit element in a View, so that I can use it with SwiftUI:
struct CustomBackButton: UIViewControllerRepresentable {
typealias UIViewControllerType = ViewController
@Binding var title: String
func makeUIView(context: Context) -> UIBarButtonItem {
return UIBarButtonItem()
}
func updateUIView(_ uiView: UIBarButtonItem, context: Context) {
uiView.title = title
}
}
It's obviously not working and I'm currently unsure how to actually make it work.
My ideal scenario would be that CustomBackButton
would work such that I can use it within SwiftUI like this:
var body: some View {
NavigationView {
Text("Page with no title")
.navigationBarItems(leading: CustomBackButton(title: "Back"))
.navigationBarTitle("", displayMode: .large)
}
}
What do I have to do to properly wrap CustomBackButton
into a SwiftUI View
?