如何在 SwiftUI 中添加自定义导航栏后退按钮

bon*_*912 2 ios swift swiftui

我一直在尝试查找如何在 SwiftUI 中添加自定义导航栏后退按钮,但我得到了这种奇怪的行为,即默认行为仍然出现在显示自定义行为之前。有谁知道添加它的正确方法?

这是我尝试过的。

var body: some View {
        NavigationView {
            ZStack {
               Color.background.edgesIgnoringSafeArea(.all)
               NavigationLink(destination: UserDetailsView()) {
                        Text("Continue")
                            .foregroundColor(.background)
                            .font(.title)
                            .fontWeight(.semibold)
                    }
                    .frame(width: 250, height: 60, alignment: .center)
                    .background(Color.white)
                    .cornerRadius(40)
                    .padding(.top, 50)
            }
            .navigationBarTitle("", displayMode: .automatic)
            .navigationBarHidden(true)
        }
      }
Run Code Online (Sandbox Code Playgroud)

在这里,当我使用下面的代码隐藏后退按钮时,它甚至根本没有隐藏。

.navigationBarBackButtonHidden(true)
Run Code Online (Sandbox Code Playgroud)

在详细信息屏幕中

  var body: some View {
        NavigationView {
            VStack {
                ZStack {
                    Rectangle()
                        .foregroundColor(.clear)
                        .background(gradient)
                        .edgesIgnoringSafeArea(.all)

                    Text("Hello")
                }
            }
            .navigationBarItems(leading: BackButton(presentationMode: presentationMode))
        }
    }
Run Code Online (Sandbox Code Playgroud)

自定义后退按钮如下所示

struct BackButton: View {
    var presentationMode : Binding<PresentationMode>

    var body: some View {
        Button(action: {
            self.presentationMode.wrappedValue.dismiss()
        }) {
            HStack {
                Image(Icon.leftArrow)
                    .aspectRatio(contentMode: .fit)
                    .foregroundColor(.black)
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是它的样子 在此输入图像描述

Bo *_*ese 5

感谢您的提示。它对我有用......但是添加后

.navigationBarItems(leading:  ... 
Run Code Online (Sandbox Code Playgroud)

滑动返回不再起作用。我猜这是 SwiftUI 中的一个错误?

有人找到解决方法吗?