SwiftUI 如何在点击按钮时推送到下一个屏幕

kes*_*hav 2 ios ios13 swiftui xcode11

我可以使用 NavigationButton (push) 或使用 PresentationButton (present) 导航到下一个屏幕,但我想在点击 Button() 时按下

Button(action: {
// move to next screen
}) {
   Text("See More")
}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?

Roh*_*ana 5

你可以使用 NavigationLink

注意:请在真机上试用。在模拟器中有时无法正常工作。

struct MasterView: View {
    @State var selection: Int? = nil

    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
                    Button("Press me") {
                        self.selection = 1
                    }
                }
            }
        }
    }
}

struct DetailsView: View {
    @Environment(\.presentationMode) var presentation

    var body: some View {
        Group {
            Button("Go Back") {
                self.presentation.wrappedValue.dismiss()
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以使用NavigationLink以下方法来实现:

struct DetailsView: View {
    var body: some View {
        VStack {
            Text("Hello world")
        }
    }
}

struct ContentView: View {
    @State var selection: Int? = nil
    var body: some View {
        NavigationView {
            VStack {
                NavigationLink(destination: DetailsView(), tag: 1, selection: $selection) {
                    Button("Press me") {
                        self.selection = 1
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)