swift 如何在单击菜单按钮时显示警报

g6ll5ycj  于 2023-02-07  发布在  Swift
关注(0)|答案(2)|浏览(213)
Menu{
                               Button("Profile", action: {})
                               Button("Settings", action: {})
                    Button(action: {
                               self.showingAlert = true
                           }, label: {
                               Text("Logout")
                           })
                    
                } label: {
                    Button(action: {
                        
                    }) {
                        Image( "icon-menu").imageScale(.large)
                            
                    }
                }.alert(isPresented:$showingAlert){
                    Alert(title: Text("Logout?"), message: Text("Are you sure you want to logout?"), primaryButton: .default(Text("Ok"), action: {
                       
                       
                    }), secondaryButton: .cancel())
                }

点击退出时没有显示警报。有人能帮助解决这个问题吗
我需要在单击菜单项时显示警报。但它不起作用

uz75evzq

uz75evzq1#

您的代码对我来说运行良好。这是我在真实的设备ios 16.3和macCatalyst(macos 13.2)上进行测试时使用的代码

struct ContentView: View {
    @State var showingAlert = false
    
    var body: some View {
        Menu {
            Button("Profile", action: {})
            Button("Settings", action: {})
            Button(action: { showingAlert = true }, label: {
                Text("Logout")
            })
        } label: {
            Button(action: {  }) {
                Image(systemName: "ellipsis.circle").imageScale(.large)
            }
        }.alert(isPresented:$showingAlert){
            Alert(title: Text("Logout?"),
                  message: Text("Are you sure you want to logout?"),
                  primaryButton: .default(Text("Ok"), action: { }),
                  secondaryButton: .cancel())
        }
    }
}
yacmzcpb

yacmzcpb2#

为注销操作创建一个函数

struct ContentView: View {
var body: some View {
    Menu{
              Button("Profile", action: {})
              Button("Settings", action: {})
              Button("Logout", action: logoutAction)
    }
}

func logoutAction() {
}}

在logoutAction方法中添加警报相关调用

相关问题