SwiftUI - 如何关闭工作表视图,同时关闭该视图 [英] SwiftUI - How to close the sheet view, while dismissing that view
问题描述
我要实现的功能.例如,来自 Apple 的查找"视图.
I want to achieve the function. Like, "Look up" view that is from Apple.
我的目标是当工作表视图通过导航推送另一个视图时,用户可以点击导航项按钮来关闭工作表视图.比如,下面这个 gif.
My aim is when the sheet view push another view by navigation, the user can tap the navigation item button to close the sheet view. Like, this below gif.
我尝试实现这个功能.
我发现了用户点击完成"按钮时的问题.该应用程序不会关闭工作表视图.它只会将视图弹出到父视图.比如,下面这个 gif.
I found a problem that is when the user tap the "Done" button. The App doesn't close the sheet view. It only pop the view to parent view. Like, this below gif.
这是我的代码.
import SwiftUI
struct ContentView: View {
@State var isShowSheet = false
var body: some View {
Button(action: {
self.isShowSheet.toggle()
}) {
Text("Tap to show the sheet")
}.sheet(isPresented: $isShowSheet) {
NavView()
}
}
}
struct NavView: View {
var body: some View {
NavigationView {
NavigationLink(destination: NavSubView()) {
Text("Enter Sub View")
}
} .navigationViewStyle(StackNavigationViewStyle())
}
}
struct NavSubView: View {
@Environment(.presentationMode) var presentationMode
var body: some View {
Text("Hello")
.navigationBarItems(trailing:
Button(action: {
self.presentationMode.wrappedValue.dismiss()
}){
Text("Done")
}
)
}
}
我是如何实现这个功能的?:)请帮帮我,谢谢.:)
How did I achieve this function? :) Please help me, thank you. :)
推荐答案
更新: 恢复原始版本 - 提供以下更改应按预期对主题启动器的代码进行.经测试可与 Xcode 13/iOS 15 配合使用
UPDATE: Restored original version - provided below changes should be done, as intended, to the topic starter's code. Tested as worked with Xcode 13 / iOS 15
由于工作表中的导航可能足够长并且关闭可能不是在所有导航子视图中,我更喜欢使用环境来仅在需要的地方指定关闭功能,而不是通过所有导航堆栈传递绑定.
As navigation in sheet might be long enough and closing can be not in all navigation subviews, I prefer to use environment to have ability to specify closing feature only in needed places instead of passing binding via all navigation stack.
这是可能的方法(使用 Xcode 11.2/iOS 13.2 测试)
Here is possible approach (tested with Xcode 11.2 / iOS 13.2)
- 定义环境键来存储工作表状态
struct ShowingSheetKey: EnvironmentKey {
static let defaultValue: Binding<Bool>? = nil
}
extension EnvironmentValues {
var showingSheet: Binding<Bool>? {
get { self[ShowingSheetKey.self] }
set { self[ShowingSheetKey.self] = newValue }
}
}
- 将此环境值设置为工作表内容的根,以便在声明时在任何子视图中都可用
}.sheet(isPresented: $isShowSheet) {
NavView()
.environment(.showingSheet, self.$isShowSheet)
}
- 声明 &仅在将要使用的子视图中使用环境值
struct NavSubView: View {
@Environment(.showingSheet) var showingSheet
var body: some View {
Text("Hello")
.navigationBarItems(trailing:
Button("Done") {
self.showingSheet?.wrappedValue = false
}
)
}
}
这篇关于SwiftUI - 如何关闭工作表视图,同时关闭该视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!