どうも、ちょげ(@chogetarou)です。
Alertを閉じる際に何かしらの処理をする方法を紹介します。
方法

alert修飾子
alert修飾子の場合は、alert修飾子の引数「actions」のButtonを使います。
具体的には、alert修飾子の引数「actions」内のButtonに閉じる際の処理を追加します。
Button(・・・)
.alert("タイトル",
isPresented: $showAlert,
actions: {
Button("ボタン"){/*閉じる際の処理*/}
・・・
},
message: {
//メッセージ
}
)
使用例
struct ContentView: View {
@State var showAlert = false;
var body: some View {
VStack {
Button(action: {
showAlert = true;
}){
Text("Show")
}
.alert("Title",
isPresented: $showAlert,
actions: {
Button("OK"){
print("OK")
}
Button("Delete",role: .destructive) {
print("Delete")
}
Button("Cancel", role: .cancel) {
print("Cancel")
}
},
message: {
Text("This is Message")
}
)
}
}
}
Alert
Alertの場合は、Alert.Buttonの値のクロージャを使います。
まず、Alertの引数で、Alert.Buttonの値を指定します。
そして、Alert.Buttonの値にクロージャを追加し、クロージャー内に閉じる際の処理を指定します。
Button(・・・)
.alert(isPresented: $showAlert) {
Alert(title: Text("タイトル"),
message: Text("本文"),
primaryButton: .default(Text("ボタン")){/*閉じる際の処理*/},
secondaryButton: ボタン2)
)
}
使用例
struct ContentView: View {
@State var showAlert = false;
var body: some View {
VStack {
Button(action: {
showAlert = true;
}){
Text("Show")
}
.alert(isPresented: $showAlert) {
Alert(title: Text("Title"),
message: Text("This is message."),
primaryButton: .default(Text("OK")){
print("Okで閉じる")
},
secondaryButton: .cancel(Text("Cancel")){
print("Cancelで閉じる")
}
)
}
}
}
}
コメント