gpt4 book ai didi

ios - 从 swiftUI 中的另一个 View 中关闭模态视图

转载 作者:行者123 更新时间:2023-11-29 05:15:58 34 4
gpt4 key购买 nike

我想在 SwiftUI 中关闭模态视图,但我做不到

这是我的代码:

内容 View :

import SwiftUI

enum Destination {
case modal
}

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

@State private var showModal = false

var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack{
SubscribeButtonView(buttonTitle: "Modal", destination: .modal, showModal: $showModal)
.padding(.top, 50)
.padding(.leading, 30)
.padding(.trailing, 30)
Spacer()
}
}
.navigationBarTitle(Text("Menu"))
}
}
}

模态视图:

import SwiftUI

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

var body: some View {
NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading) {
Spacer()
SaveButtonView(origin: .modal)
Spacer()
}
.padding(.leading, 20)
.padding(.trailing, 20)
}
.navigationBarTitle("Modal")
.navigationBarItems(trailing: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
})
}
}
}

订阅按钮 View :

import SwiftUI

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

var buttonTitle: String
var destination: Destination

@Binding var showModal: Bool

var body: some View {
Button(action: {
self.showModal.toggle()
}) {
HStack {
Image(systemName: "plus.circle")
.font(.body)
Text(buttonTitle)
}
}.sheet(isPresented: $showModal) {
if self.destination == .modal {
ModalView()
}
}
.padding()
}
}

保存按钮 View :

import SwiftUI

struct SaveButtonView: View {
@Environment(\.presentationMode) var presentationMode
var origin: Destination

var body: some View {
Button(action: {
//THIS IS NOT WORKING
self.presentationMode.wrappedValue.dismiss()
}) {
HStack {
Text("Save")
}
}
.padding()
}
}

我尝试创建一个非常简单的新项目,只有一种状态来调用模态、菜单、模态和两个按钮,并且效果很好。我不明白为什么它在上面的代码中不起作用

有人遇到同样的问题吗?

最佳答案

您应该从ModalView绑定(bind)presentationMode。

         struct SaveButtonView: View {
//@Environment(\.presentationMode) var presentationMode
@Binding var presentationMode : PresentationMode
var origin: Destination

var body: some View {
Button(action: {
//THIS IS NOT WORKING
self.$presentationMode.wrappedValue.dismiss()
}) {
HStack {
Text("Save")
}
}
.padding()
}
}


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

var body: some View {

NavigationView {
ScrollView(.vertical, showsIndicators: false) {
VStack(alignment: .leading) {
Spacer()
SaveButtonView( presentationMode: self.presentationMode, origin: .modal)
Spacer()
}
.padding(.leading, 20)
.padding(.trailing, 20)
}
.navigationBarTitle("Modal")
.navigationBarItems(trailing: Button(action: {
self.presentationMode.wrappedValue.dismiss()
}) {
Text("Cancel")
})
}
}
}

关于ios - 从 swiftUI 中的另一个 View 中关闭模态视图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59183727/

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