gpt4 book ai didi

xcode - 是否可以在 SwiftUI 菜单上有一个确认对话框?

转载 作者:行者123 更新时间:2023-12-05 04:39:39 25 4
gpt4 key购买 nike

我见过一个使用 Menu 的应用程序当你按下 a 按钮时,系统会要求我“确认”。这促使我重构我的应用程序:


@State var confirmDeletion: Bool = false

VStack {

Button(role: .destructive) {
self.confirmDeletion = true
} label: {
Spacer()

Text("Delete")

Spacer()
}.confirmationDialog(
"Are you sure?",
isPresented: $confirmDeletion,
titleVisibility: .visible
) {
Button("Yes", role: .destructive) {

DispatchQueue.main.async {
Task {

await doSomeAsynWork()
}
}
}

Button("Cancel", role: .cancel) {}
}
}

这很好用。现在使用菜单进行重构:


Menu {
[..] // other buttons

Button(role: .destructive) {
print("I was called... and that's it")
self.confirmDeletion = true

} label: {
Label("Delete", systemImage: "trash")
}.confirmationDialog(
"Are you sure?",
isPresented: $confirmDeletion,
titleVisibility: .visible
) {
Button("Yes", role: .destructive) {

DispatchQueue.main.async {
Task {

await doSomeAsynWork()
}
}
}

Button("Cancel", role: .cancel) {}
}

} label: {
Label("Menu", systemImage: "line.horizontal.3.decrease.circle")
}

我知道当您按下任何菜单按钮时,它会立即关闭,这就是 confirmationDialog 不起作用的原因。我可以用菜单实现 confirmationDialog 吗?

最佳答案

将它移到 Menu 之外,例如

Menu {
[..] // other buttons

Button(role: .destructive) {
print("I was called... and that's it")
self.confirmDeletion = true

} label: {
Label("Delete", systemImage: "trash")
}

} label: {
Label("Menu", systemImage: "line.horizontal.3.decrease.circle")
}
.confirmationDialog( // << here !!
"Are you sure?",
isPresented: $confirmDeletion,
titleVisibility: .visible
) {
Button("Yes", role: .destructive) {

DispatchQueue.main.async {
Task {

await doSomeAsynWork()
}
}
}

Button("Cancel", role: .cancel) {}
}

关于xcode - 是否可以在 SwiftUI 菜单上有一个确认对话框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70405712/

25 4 0