问题
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
?
回答1:
If you're just trying to have custom text, then no need to bother with UIKit. Here's how you can make a custom back button in SwiftUI:
struct ViewWithCustomBackButton: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
HStack {
...
}
.navigationBarTitle(Text("Your View"), displayMode: .inline)
// Hide the system back button
.navigationBarBackButtonHidden(true)
// Add your custom back button here
.navigationBarItems(leading:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image(systemName: "arrow.left.circle")
Text("Go Back")
}
})
}
}
You can also check out the answers here for more info: Custom back button for NavigationView's navigation bar in SwiftUI
来源:https://stackoverflow.com/questions/61938231/how-to-wrap-a-uibarbuttonitem-in-a-swiftui-view