我可以使用 NavigationButton(推送)或使用 PresentationButton(呈现)导航到下一个屏幕,但我想在点击 Button() 时推送
Button(action: {
// move to next screen
}) {
Text("See More")
}
有办法吗?
你可以使用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()
}
}
}
}
如您所见,要显示新视图,添加NavigationLink
with isActive: $pushView
using<.hidden()>
以隐藏导航“箭头”。
接下来添加Text("See More")
以tapGesture
使文本响应点击。pushView
当您单击“查看更多”文本时,变量将更改 (false => true)。
import SwiftUI
struct ContentView: View {
@State var pushView = false
var body: some View {
NavigationView {
List {
HStack{
Text("test")
Spacer()
NavigationLink(destination: NewView(), isActive: $pushView) {
Text("")
}.hidden()
.navigationBarTitle(self.pushView ? "New view" : "default view")
Text("See More")
.padding(.trailing)
.foregroundColor(Color.blue)
.onTapGesture {
self.pushView.toggle()
}
}
}
}
}
}
struct NewView: View {
var body: some View {
Text("New View")
}
}
您可以使用它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
}
}
}
}
}
}
要点击按钮并导航到下一个屏幕,您可以使用 NavigationLink,如下所示
NavigationView{
NavigationLink(destination: SecondView()) {
Text("Login")
.padding(.all, 5)
.frame(minWidth: 0, maxWidth: .infinity,maxHeight: 45, alignment: .center)
.foregroundColor(Color.white)
}
}