Reputation: 476
I would like to ask you how can I show alert to user. I just tried:
.navigationBarItems(trailing: Button(action: {
let alert = Alert(title: Text("Add category"), message: Text("Do you want add category?"), primaryButton: Alert.Button.default(Text("Yes"), onTrigger: {
self.sceneries[0].sceneries.append(Scenery(name: "Name", imageName: "1"))
}), secondaryButton: Alert.Button.cancel())
self.presentation(self.$isShownAlert) { () -> Alert in
return alert
}
}, label: {
Text("Add category")
}))
But it shows me that it's unused and alert didn't appear...
Upvotes: 1
Views: 1217
Reputation: 1267
Answers above are already deprecated. Use this instead:
@State var showsAlert = false
var body: some View {
NavigationView {
List {
Text("Item 1")
Text("Item 2")
Text("Item 3")
}
.navigationBarTitle("My List", displayMode: .inline)
.navigationBarItems(trailing:
Button(action: {
self.showsAlert = true
}, label: {
Text("Show Alert")
}).alert(isPresented: self.$showsAlert) {
Alert(title: Text("Hello World"))
}
)
}
}
Note the use of .alert
instead of .presentation
.
Upvotes: 0
Reputation: 19758
To display an alert with two buttons you can do like below:
@State var showAlert = false
let alert = Alert(title: Text("Title"), message: Text("Alert message"),
primaryButton: Alert.Button.default(Text("OK"),
onTrigger: {
print("OK button tapped")
}
),
secondaryButton: Alert.Button.cancel()
)
var body: some View {
NavigationView {
Text("Content")
.navigationBarItems(trailing: Button(action: {
self.showAlert = true
}, label: {
Text("Show Alert")
}).presentation(self.$showAlert, alert: {
return alert
})
)
}
}
Result:
Upvotes: 1
Reputation: 22856
You need to call presentation
API on top of the view that should display the alert.
The best way to accomplish this is to have a @State
variable, that tells SwiftUI whether the alert should be displayed or not.
The Button
action would then set it to true
, thus invalidating body
, and triggering a view rebuilding.
struct ContentView : View {
@State var showAlert = false
var body: some View {
NavigationView {
List(0...10) { value in
Text(verbatim: "\(value)")
}
.navigationBarItems(leading: EmptyView(), trailing: Button(action: {
self.showAlert = true
}) {
Text(verbatim: "Show alert")
})
.navigationBarTitle(Text(verbatim: "A List"))
}
.presentation($showAlert) {
return Alert(title: Text(verbatim: "An Alert"))
}
}
}
In this example, the button sets the @State
to true,
and presentation
is called on the navigation view.
Result:
Upvotes: 3