[英]SwiftUI .actionSheet() doesn't always present
我遇到的問題源於一個操作表中有一個按鈕,該按鈕打開另一個操作表附加到 ZStack 的不同子視圖。 我不確定為什么,但有時會出現第二個操作表,有時不會。 我認為將 state 更改代碼包裝在 DispatchQueue.main.async { } 中會在主線程上運行代碼,從而解決此問題,但有時,當按下“顯示 AS2”按鈕時,第二個操作表不會出現. 非常感謝對此問題的任何幫助。
我有一些看起來像這樣的東西:
我有一個帶有 2 state 變量的普通視圖:
@State var showActionSheet1 = false @State var showActionSheet2 = false
視圖的主體如下所示:
ZStack {
HStack {
Spacer()
Button(action: {
showActionSheet1 = true
}, label: {
}).actionSheet(isPresented: $showActionSheet1) {
ActionSheet(
title: Text("Select an option"),
buttons: [
.cancel(),
.default(Text("Tap to Do Something")) {
print("Do something")
},
.default(Text("Show AS2")) {
//showing the other action sheet
DispatchQueue.main.async {
showActionSheet2 = true
}
}
]
)
}
}
VStack {
Spacer()
HStack {
Spacer()
Text("Element")
}
}.actionSheet(isPresented: $showActionSheet2) {
ActionSheet(
title: Text("Select an option"),
buttons: [
.cancel(),
.default(Text("Tap to Do Something on second sheet")) {
print("Do something")
},
.default(Text("tap to do something on second sheet 2")) {
//showing the other action sheet
print("Do something 2")
}
]
)
}
}
它在屏幕上只能是一個 ActionSheet,當一個關閉時,它需要時間(由於動畫)從屏幕上消失。 那時無法顯示第二個 ActionSheet。
解決方案是延遲一點激活第二張紙。 (實際上在真正的最終用戶流程中很少需要,但最好考慮這些細節)
.default(Text("Show AS2")) {
//showing the other action sheet
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { // << here !!
showActionSheet2 = true
}
}
@Asperi 是對的。 每個視圖必須只有一個.actionSheet。
您可以使用三元運算符來實現這一點。
struct ActionSheetExample {
@State var showActionSheet: Bool
@State var isSheetTypeOne: Bool
var body: some View {
ZStack {
VStack(spacing: 10) {
Button("Main Sheet") {
isSheetTypeOne = true
showActionSheet = true
}
}
.actionSheet(isPresented: $showActionSheet) {
isSheetTypeOne ? ActionSheet(
title: Text("Select environment"),
buttons: [
.default(Text("Production")) {
isSheetTypeOne = false
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
showActionSheet = true
}
},
.default(Text("Staging")) {
// Perform some action
},
]
) : ActionSheet(
title: Text("Select your login type"),
buttons: [
.default(Text("Normal Login")) {
// Perform some action
},
.default(Text("Onboarding")) {
// Perform some action
}
]
)
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.