gpt4 book ai didi

swiftui - 如何在没有导航 View 或弹出窗口的情况下切换 View ?

转载 作者:行者123 更新时间:2023-12-03 16:55:49 43 4
gpt4 key购买 nike

我试图改变一个 View ,而没有像你在 swift 中使用 segue 时那样。但我想出的唯一解决方案是使用导航栏 navigationBar 或弹出框。

struct view1: View {

var body: some View{

Button(action: {
// go to view2``
}) {
Text("press")
}

}
}
struct view2: View {

var body: some View{
Text("yeay")

}
}

最佳答案

如果您只想隐藏导航栏,这很容易:

import SwiftUI

struct View2: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>

var body: some View {
VStack {
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("POP")
}
}
.navigationBarTitle("")
.navigationBarBackButtonHidden(true)
.navigationBarHidden(true)
}
}

struct ContentView: View {
var body: some View {
NavigationView {
NavigationLink(destination: View2()) {
Text("PUSH")
.navigationBarTitle("")
.navigationBarHidden(true)
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

相反,如果您想摆脱 NavigationViewNavigationLink您必须实现自己的自定义导航。它有点复杂。以下只是两个 View 之间推送/弹出转换的简单示例。
import SwiftUI

struct View2: View {
@Binding var push: Bool

var body: some View {
ZStack {
Color.yellow
Button(action: {
withAnimation(.easeOut(duration: 0.3)) {
self.push.toggle()
}
}) {
Text("POP")
}
}
.edgesIgnoringSafeArea(.all)
}
}

struct View1: View {
@Binding var push: Bool

var body: some View {
ZStack {
Color.green
Button(action: {
withAnimation(.easeOut(duration: 0.3)) {
self.push.toggle()
}
}) {
Text("PUSH")
}
}
.edgesIgnoringSafeArea(.all)
}
}

struct ContentView: View {
@State private var push = false

var body: some View {
ZStack {
if !push {
View1(push: $push)
.transition(.asymmetric(insertion: .move(edge: .leading), removal: .move(edge: .leading)))
}

if push {
View2(push: $push)
.transition(.asymmetric(insertion: .move(edge: .trailing), removal: .move(edge: .trailing)))
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}

关于swiftui - 如何在没有导航 View 或弹出窗口的情况下切换 View ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58560649/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com