どうも、ちょげ(@chogetarou)です。
Alertに複数のボタンを表示する方法を紹介します。
方法

Alertに複数のボタンを表示する方法は、2つあります。
alert(_, isPresented, actions, message)
1つは、「alert(_, isPresented, actions, message)」修飾子を使う方法です。
まず、Buttonなどにalert修飾子を付与します。
そして、alert修飾子に第1引数にタイトルとする文字列、他の引数に以下のものを指定します。
- isPresented : 表示・非表示の変数の参照
- actions : クロージャーでボタンを指定
- message : アラート本文のビュー
Button(・・・)
.alert("タイトル",
isPresented: $showAlert,
actions: {
Button(・・・)
Button(・・・)
~~~~~~~省略~~~~~~~~
},
message: {
//Alertの本文
}
)
alert修飾子の引数「actions」のクロージャーに指定したボタンが、Alertに表示されます。
使用例

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"){}
Button("Delete",role: .destructive) {}
Button("Cancel", role: .cancel) {}
},
message: {
Text("This is Message")
}
)
}
}
}
Alert(title, message, primaryButton, secondaryButton)
もう1つは、Alert(title, message, primaryButton, secondaryButton)を使う方法です。
まず、Buttonなどにalert修飾子を付与し、第1引数「isPresented」に変数の参照を指定します。
そして、alert修飾子のクロージャーに「Alert(title, message, primaryButton, secondaryButton)」を指定します。
Button(・・・)
.alert(isPresented: $showAlert) {
Alert(title: Text("タイトル"),
message: Text("本文"),
primaryButton: ボタン,
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")),
secondaryButton: .cancel(Text("Cancel"))
)
}
}
}
}
まとめ
Alertに複数のボタンを表示する方法は、次の2つです。
- alert(_, isPresented, actions, message)修飾子を使う方法
- Alert(title, message, primaryButton, secondaryButton)を使う方法
コメント