我想问问你我怎么能显示警告用户。 我只是想:
.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")
}))
但它让我发现,它的使用,仍在警戒没有出现...
你需要调用presentation
API在应该显示警报视图的顶部。
做到这一点,最好的办法是有一个@State
变量,告诉SwiftUI是否应显示或不报警。
该Button
然后行动将其设置为true
,因而无效body
,并触发浏览重建。
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"))
}
}
}
在该示例中,按钮设置@State
为真,并且presentation
被称为上的导航图。
结果:
要显示有两个按钮,你可以做象下面这样的警告:
@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
})
)
}
}
结果: