swift custom alert function code example
Example 1: show alert swiftui
struct ContentView: View {
@State var showsAlert = false
var body: some View {
Button(action: {
self.showsAlert.toggle()
}) {
Text("Show Alert")
}
.alert(isPresented: self.$showsAlert) {
Alert(title: Text("Hello"))
}
}
}
Example 2: how to use 2 alerts in swiftui
enum ActiveAlert {
case first, second
}
struct ToggleView: View {
@State private var showAlert = false
@State private var activeAlert: ActiveAlert = .first
var body: some View {
Button(action: {
if Bool.random() {
self.activeAlert = .first
} else {
self.activeAlert = .second
}
self.showAlert = true
}) {
Text("Show random alert")
}
.alert(isPresented: $showAlert) {
switch activeAlert {
case .first:
return Alert(title: Text("First Alert"), message: Text("This is the first alert"))
case .second:
return Alert(title: Text("Second Alert"), message: Text("This is the second alert"))
}
}
}
}