[SwiftUI]Alert.Buttonにタップ処理を追加するには?

SwiftUI

どうも、ちょげ(@chogetarou)です。

Alert.Buttonにタップ処理を追加する方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

Buttonにタップ処理を追加するには、クロージャーを使います。

まず、Alert.Buttonの「(label)」の後に、クロージャを追加します。

そして、クロージャー内にタップした際の処理を追加します。

.default(Text("ラベル")){
    //タップ処理
    //.cancelと.destructiveでも同じ
}

Alert.Buttonの値にクロージャーを追加することで、Alert.Buttonにタップ処理を追加することが出来ます。

使用例

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で閉じる")
                    }
                )
            }
        }
    }
}

コメント

タイトルとURLをコピーしました