skip to Main Content
 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())
                }

Alert is not showing on the click of logout. Can someone help on this

I need to show an alert on the click of a menu item. But it is not working

2

Answers


  1. Create one function for logout action

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

    Add your alert related call inside logoutAction method

    Login or Signup to reply.
  2. your code works well for me. This is the code I used for testing, on real devices ios 16.3 and macCatalyst with 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())
            }
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search