【问题标题】:Is it possible to have a confirmationDialog on SwiftUI Menu?是否可以在 SwiftUI 菜单上有一个确认对话框?
【发布时间】:2022-01-21 02:52:19
【问题描述】:

我看到一个使用 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 吗?

【问题讨论】:

    标签: xcode swiftui xcode13


    【解决方案1】:

    把它移到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) {}
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-01-28
      • 2021-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-22
      • 2015-09-30
      相关资源
      最近更新 更多