问题描述
我有这个 ContentView 有两个不同的模式视图,所以我都使用 sheet(isPresented:)
,但似乎只有最后一个被呈现.我怎么能解决这个问题?还是无法在 SwiftUI 中的视图上使用多个工作表?
I have this ContentView with two different modal views, so I'm using sheet(isPresented:)
for both, but as it seems only the last one gets presented. How could I solve this issue? Or is it not possible to use multiple sheets on a view in SwiftUI?
struct ContentView: View {
@State private var firstIsPresented = false
@State private var secondIsPresented = false
var body: some View {
NavigationView {
VStack(spacing: 20) {
Button("First modal view") {
self.firstIsPresented.toggle()
}
Button ("Second modal view") {
self.secondIsPresented.toggle()
}
}
.navigationBarTitle(Text("Multiple modal view problem"), displayMode: .inline)
.sheet(isPresented: $firstIsPresented) {
Text("First modal view")
}
.sheet(isPresented: $secondIsPresented) {
Text("Only the second modal view works!")
}
}
}
}
以上代码编译时没有警告(Xcode 11.2.1).
The above code compiles without warnings (Xcode 11.2.1).
推荐答案
UPD
从 Xcode 12.5.0 Beta 3(2021 年 3 月 3 日)开始,这个问题不再有意义,因为现在可以有多个 .sheet(isPresented:)
或 .fullScreenCover(isPresented:)
一行,问题中显示的代码将正常工作.
UPD
Starting from Xcode 12.5.0 Beta 3 (3 March 2021) this question makes no sense anymore as it is possible now to have multiple .sheet(isPresented:)
or .fullScreenCover(isPresented:)
in a row and the code presented in the question will work just fine.
尽管如此,我发现这个答案仍然有效,因为它很好地组织了工作表并使代码干净且更具可读性 - 您有一个事实来源,而不是几个独立的布尔值
Nevertheless I find this answer still valid as it organizes the sheets very well and makes the code clean and much more readable - you have one source of truth instead of a couple of independent booleans
最好的方法,也适用于 iOS 14:
Best way to do it, which also works for iOS 14:
enum ActiveSheet: Identifiable {
case first, second
var id: Int {
hashValue
}
}
struct YourView: View {
@State var activeSheet: ActiveSheet?
var body: some View {
VStack {
Button {
activeSheet = .first
} label: {
Text("Activate first sheet")
}
Button {
activeSheet = .second
} label: {
Text("Activate second sheet")
}
}
.sheet(item: $activeSheet) { item in
switch item {
case .first:
FirstView()
case .second:
SecondView()
}
}
}
}
在此处阅读更多信息:https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:)
要隐藏工作表,只需设置 activeSheet = nil
To hide the sheet just set activeSheet = nil
奖励:如果您希望您的工作表全屏显示,请使用相同的代码,但不要使用 .sheet
编写 .fullScreenCover
Bonus:If you want your sheet to be fullscreen, then use the very same code, but instead of .sheet
write .fullScreenCover
这篇关于多个工作表(isPresented :) 在 SwiftUI 中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!