2、添加action Button到alert中
上个例子显示了Alert的基本用法。我们只显示了一个Ok。如果我们想要多个Btn呢?
本文将介绍如何添加action button到alert中。
Getting ready
新建一个SwiftUI项目:AlertsWithActions
How to do it
- 添加2个State
@State private var changeText = false
@State private var displayedText = "Tap to Change Text"
- 添加一个按钮
Button(displayedText){
changeText = true
}
- 添加alert
var body: some View {
Button(displayedText) {
changeText = true
}.alert("Changing Text", isPresented: $changeText) {
Button("Yea"){
displayedText = (displayedText == "Stay Foolish") ? "Stay Hungry" : "Stay Foolish"
}
Button("Do nothing"){}
} message: {
Text("Do you want to toggle the text?")
}
}
How it works
alert的actions闭包,可以在里面提供多个按钮,然后单独为每个按钮设置action。