问题描述
我试图关闭通过 SwiftUI 中的 .sheet
呈现的模式视图 - 由 NavigationView
中的 Button
调用navigationBarItems
,如下所示:
I am attempting to dismiss a modal view presented via a .sheet
in SwiftUI - called by a Button
which is within a NavigationView
s navigationBarItems
, as per below:
struct ModalView : View {
@Environment(\.presentationMode) var presentationMode
var body: some View {
Button(action: {
self.presentationMode.value.dismiss()
}, label: { Text("Save")})
}
}
struct ContentView : View {
@State var showModal: Bool = false
var body: some View {
NavigationView {
Text("test")
.navigationBarTitle(Text("Navigation Title Text"))
.navigationBarItems(trailing:
Button(action: {
self.showModal = true
}, label: { Text("Add") })
.sheet(isPresented: $showModal, content: { ModalView() })
)
}
}
}
点击保存"按钮时,模态不会关闭,它只会保留在屏幕上.摆脱它的唯一方法是在模态上向下滑动.
The modal does not dismiss when the Save button is tapped, it just remains on screen. The only way to get rid of it is swiping down on the modal.
打印self.presentationMode.value
的值总是显示false
,所以它似乎认为它没有被呈现.
Printing the value of self.presentationMode.value
always shows false
so it seems to think that it hasn't been presented.
这仅在从 NavigationView
呈现时发生.把它拿出来,它工作正常.
This only happens when it is presented from the NavigationView
. Take that out and it works fine.
我在这里遗漏了什么,还是测试版问题?
Am I missing something here, or is this a beta issue?
推荐答案
您需要将 .sheet
移到 Button 之外.
You need to move the .sheet
outside the Button.
NavigationView {
Text("test")
.navigationBarTitle(Text("Navigation Title Text"))
.navigationBarItems(trailing:
Button("Add") {
self.showModal = true
}
)
.sheet(isPresented: $showModal, content: { ModalView() })
}
您甚至可以将其移到 NavigationView
闭包之外.
You can even move it outside the NavigationView
closure.
NavigationView {
Text("test")
.navigationBarTitle(Text("Navigation Title Text"))
.navigationBarItems(trailing:
Button("Add") { self.showModal = true }
)
}
.sheet(isPresented: $showModal, content: { ModalView() })
请注意,如果您有一个简单的文本按钮,您还可以简化 Button 调用.
Notice you can also simplify the Button call if you have a simple text button.
这篇关于SwiftUI 关闭从 NavigationView 呈现的模式表(Xcode Beta 5)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!