我找不到任何关于如何以编程方式制作 SwiftUI 中呈现视图的 弹出 或 消失 的参考资料。
在我看来,唯一的方法是使用模态的已集成下滑操作(如果我想禁用此功能,该怎么做?),以及导航栈的返回按钮。
有人知道解决方案吗? 您是否知道这是一个错误还是会保持这样?
这个示例使用了Beta 5发布说明中记录的新环境变量,该变量原本使用value属性。后来在后续的beta版本中更改为使用wrappedValue属性。现在,此示例已更新至GM版本。同样的概念也适用于使用.sheet修饰符呈现的模态视图的取消。
import SwiftUI
struct DetailView: View {
@Environment(\.presentationMode) var presentationMode: Binding<PresentationMode>
var body: some View {
Button(
"Here is Detail View. Tap to go back.",
action: { self.presentationMode.wrappedValue.dismiss() }
)
}
}
struct RootView: View {
var body: some View {
VStack {
NavigationLink(destination: DetailView())
{ Text("I am Root. Tap for Detail View.") }
}
}
}
struct ContentView: View {
var body: some View {
NavigationView {
RootView()
}
}
}
SwiftUI Xcode Beta 5
首先,声明@Environment,其中包含一个dismiss方法,您可以在任何地方使用它来关闭视图。
import SwiftUI
struct GameView: View {
@Environment(\.presentationMode) var presentation
var body: some View {
Button("Done") {
self.presentation.wrappedValue.dismiss()
}
}
}
从iOS 15开始,我们可以使用一个新的@Environment(\.dismiss)
:
struct SheetView: View {
@Environment(\.dismiss) var dismiss
var body: some View {
NavigationView {
Text("Sheet")
.toolbar {
Button("Done") {
dismiss()
}
}
}
}
}
(不再需要使用 presentationMode.wrappedValue.dismiss()
。)
有用的链接:
现在有一种编程方式可以弹出NavigationView,如果您愿意的话。这是beta 5版中的新功能。请注意,您不需要返回按钮。您可以以任何想要的方式编程触发DetailView中的showSelf属性。而且您不必在主视图中显示“Push”文本,那可以是一个EmptyView(),从而创建一个无形的转场。
import SwiftUI
struct ContentView: View {
var body: some View {
NavigationView {
MasterView()
}
}
}
struct MasterView: View {
@State private var showDetail = false
var body: some View {
VStack {
NavigationLink(destination: DetailView(showSelf: $showDetail), isActive: $showDetail) {
Text("Push")
}
}
}
}
struct DetailView: View {
@Binding var showSelf: Bool
var body: some View {
Button(action: {
self.showSelf = false
}) {
Text("Pop")
}
}
}
#if DEBUG
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
#endif
tag: , selection:
初始化方式而不是 isActive:
,你也可以将这个选择作为绑定变量传递,并将其设置为 nil(或其他与你的标签不同的值)以弹出视图。 - AlexMath.isDetailLink(false)
添加到根导航链接。否则,当堆栈中出现第3个视图时,选择会自动设置为nil。 - AlexMath我最近创建了一个开源项目,叫做 swiftui-navigation-stack
(https://github.com/biobeats/swiftui-navigation-stack),其中包含 NavigationStackView
,这是 SwiftUI 的一种替代导航栈。它提供了几个在代码库的自述文件中描述的功能。例如,你可以轻松地以编程方式推送和弹出视图。我将通过一个简单的例子向你展示如何实现:
首先,在 NavigationStackVew
中嵌入你的视图层次结构:
struct RootView: View {
var body: some View {
NavigationStackView {
View1()
}
}
}
NavigationStackView
为您的层次结构提供了一个有用的环境对象,称为NavigationStack
。您可以使用它来编程方式弹出视图,就像上面问题中所要求的一样:
struct View1: View {
var body: some View {
ZStack {
Color.yellow.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 1")
Spacer()
PushView(destination: View2()) {
Text("PUSH TO VIEW 2")
}
}
}
}
}
struct View2: View {
@EnvironmentObject var navStack: NavigationStack
var body: some View {
ZStack {
Color.green.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 2")
Spacer()
Button(action: {
self.navStack.pop()
}, label: {
Text("PROGRAMMATICALLY POP TO VIEW 1")
})
}
}
}
}
在这个例子中,我使用PushView
来触发轻触后推送导航。然后,在View2
中,我使用环境对象来编程式地返回。import SwiftUI
import NavigationStack
struct RootView: View {
var body: some View {
NavigationStackView {
View1()
}
}
}
struct View1: View {
var body: some View {
ZStack {
Color.yellow.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 1")
Spacer()
PushView(destination: View2()) {
Text("PUSH TO VIEW 2")
}
}
}
}
}
struct View2: View {
@EnvironmentObject var navStack: NavigationStack
var body: some View {
ZStack {
Color.green.edgesIgnoringSafeArea(.all)
VStack {
Text("VIEW 2")
Spacer()
Button(action: {
self.navStack.pop()
}, label: {
Text("PROGRAMMATICALLY POP TO VIEW 1")
})
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
RootView()
}
}
结果是:
PushView(destination: Child0(), destinationId: "destinationId") { Text("PUSH") }
然后 PopView(destination: .view(withId: "destinationId")) { Text("POP") }
。如果你以编程方式访问导航堆栈环境对象,也是同样的方法。 - superpuccio或者,如果您不想从按钮程序方式实现它,您可以在需要弹出时从视图模型中发出信号。 订阅一个@Published,每当保存完成时更改其值。
struct ContentView: View {
@ObservedObject var viewModel: ContentViewModel
@Environment(\.presentationMode) var presentationMode
init(viewModel: ContentViewModel) {
self.viewModel = viewModel
}
var body: some View {
Form {
TextField("Name", text: $viewModel.name)
.textContentType(.name)
}
.onAppear {
self.viewModel.cancellable = self.viewModel
.$saved
.sink(receiveValue: { saved in
guard saved else { return }
self.presentationMode.wrappedValue.dismiss()
}
)
}
}
}
class ContentViewModel: ObservableObject {
@Published var saved = false // This can store any value.
@Published var name = ""
var cancellable: AnyCancellable? // You can use a cancellable set if you have multiple observers.
func onSave() {
// Do the save.
// Emit the new value.
saved = true
}
}
请查看以下代码,它非常简单。
首个视图
struct StartUpVC: View {
@State var selection: Int? = nil
var body: some View {
NavigationView{
NavigationLink(destination: LoginView().hiddenNavigationBarStyle(), tag: 1, selection: $selection) {
Button(action: {
print("Signup tapped")
self.selection = 1
}) {
HStack {
Spacer()
Text("Sign up")
Spacer()
}
}
}
}
}
SecondView
struct LoginView: View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
NavigationView{
Button(action: {
print("Login tapped")
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Image("Back")
.resizable()
.frame(width: 20, height: 20)
.padding(.leading, 20)
}
}
}
}
}
struct ModalView<Content>: View where Content: View {
@Binding var isShowing: Bool
var content: () -> Content
var body: some View {
GeometryReader { geometry in
ZStack(alignment: .center) {
if (!self.isShowing) {
self.content()
}
if (self.isShowing) {
self.content()
.disabled(true)
.blur(radius: 3)
VStack {
Text("Modal")
}
.frame(width: geometry.size.width / 2,
height: geometry.size.height / 5)
.background(Color.secondary.colorInvert())
.foregroundColor(Color.primary)
.cornerRadius(20)
.transition(.moveAndFade) // associated transition to the modal view
}
}
}
}
}
我重用了来自动画视图和转换教程中的Transition.moveAndFade
。
它定义如下:
extension AnyTransition {
static var moveAndFade: AnyTransition {
let insertion = AnyTransition.move(edge: .trailing)
.combined(with: .opacity)
let removal = AnyTransition.scale()
.combined(with: .opacity)
return .asymmetric(insertion: insertion, removal: removal)
}
}
struct ContentView: View {
@State var isShowingModal: Bool = false
func toggleModal() {
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation {
self.isShowingModal = true
}
DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
withAnimation {
self.isShowingModal = false
}
}
}
}
var body: some View {
ModalView(isShowing: $isShowingModal) {
NavigationView {
List(["1", "2", "3", "4", "5"].identified(by: \.self)) { row in
Text(row)
}.navigationBarTitle(Text("A List"), displayMode: .large)
}.onAppear { self.toggleModal() }
}
}
}
这也将关闭视图
let scenes = UIApplication.shared.connectedScenes
let windowScene = scenes.first as? UIWindowScene
let window = windowScene?.windows.first
window?.rootViewController?.dismiss(animated: true, completion: {
print("dismissed")
})
struct MyView: View {
@State
var showsUp = false
var body: some View {
Button(action: { self.showsUp.toggle() }) {
Text("Pop")
}
.presentation(
showsUp ? Modal(
Button(action: { self.showsUp.toggle() }) {
Text("Dismiss")
}
) : nil
)
}
}
onDisappear(_:)
? - WeZZard
navigationLink
标签和selection
,并使用跟踪选择的environmentobject
。然后,您可以将environmentobject
的selection
设置为nil
,以从任何子视图返回到根视图。 - Super NoobNavigationView
。 - jimmy0251