変数で判定する
複数のアラートは、変数で判定して使い分けます。
struct ContentView: View {
//アラートを判別する変数
@State var whichAlert : AlertType = AlertType.first
@State var onAlert = false
var body: some View {
VStack {
Button(action: {
self.whichAlert = .first
self.onAlert = true
}) {
Text("アラート1")
}
.padding()
Button(action: {
self.whichAlert = .second
self.onAlert = true
}) {
Text("アラート2")
}
.padding()
}
.alert(isPresented: $onAlert) {
switch whichAlert {
case .first:
return Alert(title: Text("アラート1"), message: Text(""),dismissButton: .default(Text("OK")))
case .second:
return Alert(title: Text("アラート2"),message: Text(""), dismissButton: .default(Text("OK")))
}
}
}
}
//アラートの識別子
enum AlertType {
case first
case second
}
アラートを表示する前に、どのアラートを表示するのかを変数に格納します。
アラートが表示されるときに、どのアラートを表示するのかを、switch文で判定し使い分けます。
失敗する例

以下は、複数のアラートで失敗する例です。
- toolbarに入っている
- 連続表示(アラートのボタンでアラートを表示する)
- alert修飾子の重複
これらの例で使い分けようとすると、うまくいきません。
もし、うまくできなくて悩んでいるなら、これらに当てはまってないかを確認してください。

コメント