从 swiftUI 中的另一个视图中关闭模态视图
Posted
技术标签:
【中文标题】从 swiftUI 中的另一个视图中关闭模态视图【英文标题】:Dismiss modal view from another view in swiftUI 【发布时间】:2019-12-04 19:52:24 【问题描述】:我想关闭 SwiftUI 中的模态视图,但我不能
这是我的代码:
内容视图:
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")
)
订阅按钮视图:
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()
SaveButtonView:
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()
我尝试创建一个非常简单的新项目,只有一个状态来调用模式、菜单、模式和两个按钮,它工作得很好。我不明白为什么它在上面的代码中不起作用
有人遇到过同样的问题吗?
【问题讨论】:
【参考方案1】:你应该从ModalView
绑定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")
)
【讨论】:
谢谢。这真的很有帮助。在这种情况下,这对我来说是必需的,因为我的子视图包含在滚动视图中以上是关于从 swiftUI 中的另一个视图中关闭模态视图的主要内容,如果未能解决你的问题,请参考以下文章
如何以模态方式将视图添加到不在视图层次结构中的另一个视图 iOS
从 uitabbarController 视图中关闭模态视图