比方说,我在NavigationView中有一个视图,带有前导和尾随按钮。 因为从该视图可以显示两个不同的工作表,所以我使用了这样的枚举:
enum AccountActiveSheet {
case about, settings
}
此主视图在视图中具有两个@State属性,以触发工作表显示。
@State private var isSheetPresented: Bool = false
@State private var activeSheet: AccountActiveSheet = .about
每个按钮都可以触发一张纸。
var aboutButton: some View {
Button(action: {
self.activeSheet = .about
self.isSheetPresented.toggle()
}, label: {
Image(systemName: "info.circle.fill")
})
}
在导航视图的末尾,我选择了正确的表格来呈现
.sheet(isPresented: $isSheetPresented) {
self.activeSheet.sheet
}
它工作正常,并以模态显示正确的视图。
但是我在这个主视图中还有多个子视图,当点击一个按钮时,它们可以显示表格。在这种情况下,不会显示由子视图管理的工作表(即@State变量,用于跟踪子视图提供的工作表的$ isSheetPresented +内容)。没发生什么事。似乎超级视图工作表修饰符阻止子视图显示工作表。
是否可以同时具有超级视图和子视图管理工作表演示文稿?
enum AccountActiveSheet {
case about, settings
@ViewBuilder
var sheet: some View {
switch self {
case .about: Text("About")
case .settings: Text("Settings")
}
}
}
struct AccountView: View {
@State private var isSheetPresented: Bool = false
@State private var activeSheet: AccountActiveSheet = .about
var aboutButton: some View {
Button(action: {
self.activeSheet = .about
self.isSheetPresented.toggle()
}, label: {
Image(systemName: "info.circle.fill")
})
}
var settingsButton: some View {
Button(action: {
self.activeSheet = .settings
self.isSheetPresented.toggle()
}, label: {
Image(systemName: "gearshape.fill")
})
}
var body: some View {
NavigationView {
VStack {
Subview()
}
.navigationBarTitle("Account", displayMode: .inline)
.navigationBarItems(leading: aboutButton, trailing: settingsButton)
.sheet(isPresented: $isSheetPresented) {
self.activeSheet.sheet
}
}
}
}
struct Subview: View {
@State var isSheetPresented: Bool = false
var body: some View {
Button("Present sheet") {
self.isSheetPresented.toggle()
}
.sheet(isPresented: $isSheetPresented) {
Text("Subview")
}
}
}
答案 0 :(得分:0)
将根视图表移出NavigationView
(已通过Xcode 12.1 / iOS 14.1测试)
var body: some View {
NavigationView {
VStack {
Subview()
}
.navigationBarTitle("Account", displayMode: .inline)
.navigationBarItems(leading: aboutButton, trailing: settingsButton)
}
.sheet(isPresented: $isSheetPresented) { // << here !!
self.activeSheet.sheet
}
}