首页 > 解决方案 > 如何在 SwiftUI 视图中包装 UIBarButtonItem?

问题描述

我正在尝试为NavigationBar我可以放置我喜欢的任何文本的位置制作一个自定义的后退按钮。我的主要用例是我的一些视图没有标题,当我从中单击新视图时,导航栏中新视图的后退按钮没有文本,只有一个箭头。它使用户很难点击它。我希望设置一个自定义后退按钮,其中包含文本“Back”,但也有后退按钮图标,并且与 SwiftUI 的动画机制完美配合。

这是我目前尝试将 UIKit 元素包装在 View 中,以便我可以将它与 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
    }
}

它显然不起作用,我目前不确定如何使其真正起作用。

我的理想方案是CustomBackButton这样我可以在 SwiftUI 中像这样使用它:

    var body: some View {
        NavigationView {
            Text("Page with no title")
                .navigationBarItems(leading: CustomBackButton(title: "Back"))
                .navigationBarTitle("", displayMode: .large)
        }
    }

我需要做什么才能正确包装CustomBackButton到 SwiftUI 中View

标签: uikitswiftui

解决方案


如果您只是想拥有自定义文本,则无需为 UIKit 操心。以下是在 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")
                }
        })
    }
}

您还可以在此处查看答案以获取更多信息:SwiftUI 中 NavigationView 导航栏的自定义后退按钮


推荐阅读