[SwiftUI]ActionSheet(アクションシート)を表示するには?

SwiftUI

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

ActionSheetを表示する方法を紹介します。

スポンサーリンク

方法

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

ActionSheetを表示する方法は、2つあります。

confirmationDialog

1つは、confirmationDialog修飾子を使う方法です。

まず、ButtonなどにconfimarionDialog修飾子を付与します。

そして、comfiramationDialogの引数にActionSheetの設定を指定します。

Button(・・・)
    .confirmationDialog(
        ~~~引数でActionSheetの設定~~~
    )

confirmationDialogの引数には、さまざまなものがあります。

その中で共通しているのは、「isPresented」です。

引数「isPresented」には、ActionSheetの表示・非表示を切り替えるBool型の変数を指定します。

使用例

struct ContentView: View {
    @State var showSheet = false;
    var body: some View {
        VStack {
            Button(action: {
                showSheet = true;
            }){
                Text("Show")
            }
            .confirmationDialog(
                "Title",
                isPresented: $showSheet,
                actions: {
                    Button("OK"){}
                    Button("Delete", role: .destructive){}
                    Button("Cancel", role: .cancel) {}
                },
                message: {
                    Text("This is action sheet.")
                }
            )
        }
    }
}

actionSheet

もう1つは、actionSheet修飾子を使う方法です。

まず、ButtonなどにactionSheet修飾子を付与します。

次に、actionSheet修飾子の引数「isPresented」に、表示・非表示の変数の参照を指定します。

そして、actionSheetのクロージャーにActionSheetを指定します。

Button(・・・)
    .actionSheet(isPresented: $isShow) {
        ActionSheet(・・・)
    }

ActionSheetの引数には、次のものがあります。

  • title : タイトル
  • message : メッセージ
  • buttons : ボタン(ActionSheet.Buttonの値)の配列

使用例

struct ContentView: View {
    @State var showSheet = false;
    var body: some View {
        VStack {
            Button(action: {
                showSheet = true;
            }){
                Text("Show")
            }
            .actionSheet(isPresented: $showSheet) {
                ActionSheet(
                    title: Text("タイトル"),
                    message: Text("メッセージ本文です。"),
                    buttons: [
                        .default(Text("OK")),
                        .cancel(Text("Cancel"))
                    ]
                )
            }
        }
    }
}

まとめ

ActionSheetを表示する方法は、次の2つです。

  • confimationDialog修飾子を使う方法
  • actionSheet修飾子を使う方法

コメント

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