我一直在尝试查找如何在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)
        }
      }

在这里,当我使用下面的代码隐藏后退按钮时,它甚至根本不会隐藏。
.navigationBarBackButtonHidden(true)

在详细画面
  var body: some View {
        NavigationView {
            VStack {
                ZStack {
                    Rectangle()
                        .foregroundColor(.clear)
                        .background(gradient)
                        .edgesIgnoringSafeArea(.all)

                    Text("Hello")
                }
            }
            .navigationBarItems(leading: BackButton(presentationMode: presentationMode))
        }
    }

自定义后退按钮如下所示
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)
            }
        }
    }
}

这是它的样子
ios - 如何在SwiftUI中添加自定义导航栏后退按钮-LMLPHP

最佳答案

以下配置有效(已通过Xcode 11.2 / iOS 13.2测试)

var body: some View {
  NavigationView {
      ZStack {
         // ...
         NavigationLink(destination:
                           UserDetailsView()
                               .navigationBarTitle("", displayMode: .inline)
                               .navigationBarHidden(true)
         ) {
                    // ...
           }
      }
      .navigationBarTitle("", displayMode: .inline)
      .navigationBarHidden(true)
      .navigationBarBackButtonHidden(true)
  }
}

关于ios - 如何在SwiftUI中添加自定义导航栏后退按钮,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59691957/

10-12 00:22
查看更多