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...
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 totrue
, thus invalidatingbody
, and triggering a view rebuilding.In this example, the button sets the
@State
to true, andpresentation
is called on the navigation view.Result:
To display an alert with two buttons you can do like below:
Result: