SwiftUI | How to hide cancel button in alert window?

Viewed 49

While testing new alert method in iOS 15(document), I just found a weird behavior that alert has.

Description

This is the codes:

import SwiftUI

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            Button("button2", role: .destructive, action: {})
        }
    }
}

As you can see, I added only 2 buttons but SwiftUI just adds Cancel button at the end of the buttons.

However, it doesn't happen when any of the buttons doesn't have a role.


import SwiftUI

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            
            Button(action: {}) {
                Text("button1")
            }
        }
    }
}

It's really weird. I even have no idea that it's intended by Apple or just a bug.

Question

Therefore my question is, how can I remove that cancel button after I added a button with a role. Is there any way to do this or I have to just accept it..

Any advice will be appreciated.

1 Answers

As role destructive button is for deletes user data, or performs an irreversible operation according to Apple docs.

In the alert view maybe because of you have a button with role .destructive so the alert default add a .cancel button. For closing the alert you should define a button with role .cancel

struct ContentView: View {
    @State var show = false
    var body: some View {
        VStack {
            Button(action: {
                show = true
            }) {
                Text("Alert")
            }
        }
        .alert("alert", isPresented: $show) {
            Button(action: {}) {
                Text("button1")
            }
            Button("button2", role: .cancel, action: {})
        }
    }
}

The result

Related