While testing new alert
method in iOS 15( document ), I just found a weird behavior that alert has.
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.
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.
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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.