SwiftUIでAlertの実装方法をまとめました。
State変数作成
Alertの表示状態を管理するStateの変数を作成します。
struct ContentView: View {
@State private var showAlert: Bool = false
var body: some View {
}
}
Buttonを押したときにAlert表示
ここでは、Buttonを作成し、タップした時にAlertを表示します。
Buttonをタップした時に、showAlertをtrueにします。
struct ContentView: View {
@State private var showAlert: Bool = false
var body: some View {
Button(action: {
showAlert = true
}) {
Text("Button")
}
}
}
Alertの作成
最後にAlertを作成します。
ここでは、キャンセルボタンとOKボタンを設定しています。
struct ContentView: View {
@State private var showAlert: Bool = false
var body: some View {
Button(action: {
showAlert = true
}) {
Text("アラート表示")
}
.alert(isPresented: $showAlert) {
Alert(
title: Text("タイトル"),
message: Text("メッセージ"),
primaryButton: .cancel(),
secondaryButton: .default(Text("OK"), action: {
// タップ時の処理
})
)
}
}
}