0

I want to add buttons in swiftUI alert at run time. Below code is not working.

struct ContentView: View {
@State private var presentAlert = false
@State private var username: String = ""

var body: some View {
    Button("Show Alert") {
        presentAlert = true
    }
    .alert("Login", isPresented: $presentAlert, actions: {
        TextField("Username", text: $username)
        Button("Cancel", role: .cancel, action: {})
        if $username.wrappedValue.count>0 {
            Button("Login", action: {})
        }
    }, message: {
        Text("Please enter your username and password.")
    })
}

}

Prabhat Pankaj
  • 192
  • 1
  • 6

1 Answers1

0

You cannot have views inside actions. For maximum control over the content and behaviour of the alert popup, I recommend just creating your own

Taken from my answer here

struct ContentView: View {
    @State private var presentAlert = false
    var body: some View {
        ZStack {
            VStack {
                // your main view
            }
            .blur(radius: presentAlert ? 15 : 0)
            if presentAlert {
                AlertView()
            }
        }
    }
}

struct AlertView: View {
    var body: some View {
        ZStack {
            RoundedRectangle(cornerRadius: 6)
                .foregroundColor(.blue)
            VStack {
                TextField("Username", text: $username)
                Button("Cancel", role: .cancel, action: {})
                // ... etc
            }
        }
    }
}
Suyash Medhavi
  • 1,135
  • 6
  • 18