Curiosity
Curiosity

Reputation: 264

How do you conditionally display buttons within a SwiftUI alert?

Say I have an alert

@State var showingAlert = false

var body: some View {
    Text("Hello, world!")
        .alert("Here's an alert with multiple possible buttons.", isPresented: $showingAlert) {
            Button("OK") {
                
            }
            Button("Another button that may or may not show") {
                
            }
        }
}

How could I display the second button based only on some condition?

I tried factoring out one button into

fileprivate func extractedFunc() -> Button<Text> {
    return Button("OK") {
        
    }
}

and this would work for conditionally displaying the button content given a fixed number of buttons, but how could optionality of buttons be taken into account?

Upvotes: 1

Views: 389

Answers (1)

jnpdx
jnpdx

Reputation: 52555

The inside of the alert works like other ViewBuilders where you can use an if clause to conditionally display views:

struct ContentView: View {
    @State var showingAlert = false
    @State var buttonCondition = false

    var body: some View {
        VStack {
            Button("Show alert") { showingAlert.toggle() }
            Button("Show second button") { buttonCondition.toggle() }
        }
        .alert("Here's an alert with multiple possible buttons.", isPresented: $showingAlert) {
            Button("OK") { }
            if buttonCondition {
                Button("Another button that may or may not show") { }
            }
        }
    }
}

If you want to extract it out to a separate function like you mentioned, you could do the following:

struct ContentView: View {
    @State var showingAlert = false
    @State var buttonCondition = false

    var body: some View {
        VStack {
            Button("Show alert") { showingAlert.toggle() }
            Button("Show second button") { buttonCondition.toggle() }
        }
        .alert("Here's an alert with multiple possible buttons.", isPresented: $showingAlert) {
            extractedButtons()
        }
    }
    
    @ViewBuilder func extractedButtons() -> some View {
        Button("OK") { }
        if buttonCondition {
            Button("Another button that may or may not show") { }
        }
    }
}

Upvotes: 1

Related Questions