使用SwiftUI上的NavigationView创建自定义后退按钮

0s0u357o  于 2022-12-10  发布在  Swift
关注(0)|答案(1)|浏览(207)

我试图在SwiftUI上创建一个自定义的后退按钮,但我不知道如何做。
其想法是隐藏左上方提供NavigationView的“Back”按钮,并创建一个具有相同功能的自定义按钮。

struct AnadirDatosViewA: View {
    @Environment(\.presentationMode) var presentation
    
    var body: some View{
        NavigationView(){
            Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
                .edgesIgnoringSafeArea(.all)
                .overlay(
                    VStack{
                        AnadirDatosExpB()
                        
                        HStack{
                            
                            NavigationLink(destination:NuevoExperimentoView()){
                                Text("Back") //HERE
                                
                                NavigationLink(destination:AnadirDatosExpA()){
                                    Text("Next")
                                        
                                }
                            }
                        }
                    }
                )
        }.navigationBarBackButtonHidden(true)
    }
}

现在我正在“作弊”通过使用视图我想去回去作为目的地,但它不一样的工作...
我能怎么办?

41zrol4v

41zrol4v1#

You can use the presentationMode var from the environment inside a Button:
See the commented example below for a possible implementation.

struct ContentView: View{
    
    var body: some View{
        // I am navigating with a Navigationlink, so there is
        // no need for it in the AnadirDatosViewA
        NavigationView {
            NavigationLink("show AnadirDatosViewA") {
                AnadirDatosViewA()
            }
        }
    }
}

struct AnadirDatosViewA: View {
    @Environment(\.presentationMode) var presentation
    
    var body: some View{
        // if you navigated to this by a Navigationlink remove the NavigationView
        Color(red: 48 / 255, green: 49 / 255, blue: 54 / 255)
            .edgesIgnoringSafeArea(.all)
            .overlay(
                HStack{
                    // This Button will dismiss the View
                    Button("Back"){
                        // with help of th presentationMode from the environment
                        presentation.wrappedValue.dismiss()
                    }
                    // This NavigationLink can forward you to another view
                    NavigationLink("Next") {
                        TextView(text: "last")
                    }
                }
                // This will hide the back Button in this View
            ).navigationBarBackButtonHidden(true)
    }
}
// HelperView
struct TextView: View{
    var text: String
    var body: some View{
        Text(text)
    }
}

相关问题