SwiftUI アラート表示

Pocket

SwiftUIのViewには.alert(isPresented: Binding<Bool>, content: () -> Alert)があります。contentにAlertを埋め込むことで下のようなアラートが表示されます。

struct Alert は、View継承ではないので .alert()の中に配置します。.alertのcontent内にそのままではprint()は入らないようです。シンプルなコーディングは下記です。

import SwiftUI

struct ShowMessage: View {
    @State var bPresented: Bool = false
    var body: some View {
        Button("Button1", action: {
            self.bPresented = true
        }).alert(isPresented: self.$bPresented, content: {
            Alert(title: Text("⚠️アラート"))
        })
    }
}

Alertにはtitle以外にも、アラートの本文を書くためのmessageや、ボタンの名称などが変更できるdismissButton・アラートボタンが押されたあとに動くactionなどの引数が設定できます。

Alert(title: Text("㊙️神のお告げ"), message: Text("あなたの過去を削除しました。"), dismissButton: .default(Text("☠️承知"), action: {
	print("過去を削除")
}))

選択できるアラート表示を作成する場合primaryButton, secondaryButtonが設定できます。

Alert(title: Text("㊙️神のお告げ"), message: Text("あなたの過去を削除しますか?"),
	primaryButton: .cancel(Text("削除しない"), action: { print("action primaryButton: .cancel") }),
	secondaryButton: .default(Text("🦠ぜひ削除"), action: { print("action secondaryButton: .default") })
)

それぞれのボタンに設定している.default() .cancel()に文字列とボタンが押された場合のactionが設定できます。ボタンに.destructive()を設定した場合ボタンの文字が赤で表示されます。

import SwiftUI

struct ShowMessage: View {
    @State var bPresented1: Bool = false
    @State var bPresented2: Bool = false
    var body: some View {
        VStack {
            Button("Button1", action: {
                self.bPresented1 = true
            }).alert(isPresented: self.$bPresented1, content: {
                Alert(title: Text("㊙️神のお告げ"), message: Text("あなたの過去を削除しますか?"),
                primaryButton: .cancel(Text("削除しない"), action: { print("action primaryButton: .cancel") }),
                secondaryButton: .destructive(Text("🦠ぜひ削除"), action: {
                    DispatchQueue.main.asyncAfter(deadline: .now() ) {
                        self.bPresented2 = true
                    }
                }))
                
            })
            Color.white.opacity(0).frame(height: 0.1).alert(isPresented: self.$bPresented2, content: {
                Alert(title: Text("⚠️エラー"), message: Text("あなたの過去は削除できません。"), dismissButton: .default(Text("OK")) )
                
            })
        }
    }
}

キャンセル付きのアラートを出したあとにアラートを表示する場合上記のように書けばうまく動作した。@State の変更は一旦メインに返さないといけないみたいだった。

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

CAPTCHA


2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED