How to wrap a UIBarButtonItem in a SwiftUI View?

我与影子孤独终老i 提交于 2020-05-24 05:03:19

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!