因此,我想使用SwiftUI呈现一个新视图,而无需用户点击按钮,因为NavigationButton
可以使用它。这是一个例子
struct ContentView : View {
var model: Model
var body: some View {
NavigationView {
Text("Hello World")
}.onAppear {
if model.shouldPresent {
// present a new view
}
}
}
}
在onAppear
中,我想包含一些将新视图推送到导航堆栈上的代码。
答案 0 :(得分:1)
这是一种将视图显示为模态的方法。
Scenario: ...
Given I drop the file to the server's UNC path
When the file is processed successfully
Then a new account is loaded
类似地,如果您希望控制是否使用变量来显示,则可以执行以下操作。
struct PresentOnloadView: View {
var body: some View {
HStack {
Text("Hey there")
}
.presentation(Modal(HelloView(), onDismiss: nil))
}
}
struct HelloView: View {
var body: some View {
Text("Whats up! ?")
}
}
答案 1 :(得分:1)
在您的视图内:
@State var present = true
var body: some View {
NavigationLink(destination: DestinationView(), isActive: $present) {
EmptyView()
}
}
导航链接加载后,此代码立即显示DestinationView
。关键部分是isActive
参数,该参数以编程方式触发向其他视图的过渡。
您可以重写如下
@State var present = false
var body: some View {
NavigationLink(destination: DestinationView(), isActive: $present) {
Button {
present = true
} label: { Text("Present") }
}
}
要手动创建导航按钮。
答案 2 :(得分:0)
您只需将逻辑放在NavigationView
中。像这样:
@State var x = true;
var body : some View {
NavigationView {
if x {
Text("Hello")
Button(action: {
self.x = false;
}, label: { Text("Click Me") })
} else {
Text("World")
}
}
}
答案 3 :(得分:0)
SwiftUI 2 / iOS 14 中的 Segue 等效项:
struct ContentView: View {
@State var showSecondView = false
var body: some View {
NavigationView {
Text("First view")
.background(NavigationLink("", destination: Text("Second view"), isActive: $showSecondView))
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showSecondView = true
}
}
}
}
struct ContentView: View {
@State private var showSecondView = false
var body: some View {
NavigationView {
if showSecondView {
Text("Second view")
} else {
Text("First view")
}
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showSecondView = true
}
}
}
}
struct ContentView: View {
@State private var showSecondView = false
var body: some View {
NavigationView {
Text("First view")
}
.sheet(isPresented: $showSecondView) {
Text("Second view")
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showSecondView = true
}
}
}
}
struct ContentView: View {
@State private var showSecondView = false
var body: some View {
NavigationView {
Text("First view")
}
.fullScreenCover(isPresented: $showSecondView) {
Text("Second view")
}
.onAppear {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
showSecondView = true
}
}
}
}
注意:我添加了 DispatchQueue.main.asyncAfter(deadline: .now() + 1)
以便您可以看到过渡。您可以删除它,过渡将立即开始。