SwiftUI アクションシート actionSheet

Pocket

ActionSheetAlertによく似ていますが、複数ボタンが作れユーザーに処理を選んでもらう場合などに利用できます。

前回Alertについて書いていますので、興味がある人はそちらも御覧ください。

下のコードは、.actionSheet()使ったシンプルな例です。

import SwiftUI

struct MessageDlg: View {
    @State var bEnable: Bool = false
    var body: some View {
        Button("Button1", action: {
            self.bEnable = true
        } ).actionSheet(isPresented: self.$bEnable) { () -> ActionSheet in
            ActionSheet(title: Text("🌀 ゾルタスクゼイアン"))
        }
    }
}

コードを実行し、Button1を押すと下のようにActionSheetが表示されます。

SimpleなActionSheet
Simpleな ActionSheet

「🌀」はButtonイメージと同じで、文字色と同じベタ塗りになります。

ActionSheetにtitleとmessageを設定すると下のような表示もできます。

ActionSheet Message付き
message引数を追加

titleとmessageのみの場合、“Cancel”ボタンしかありません。それ以外のボタンも追加できます。

struct MessageDlg: View {
    @State var bEnable: Bool = false
    var body: some View {
        Button("Button1", action: {
            self.bEnable = true
        } ).actionSheet(isPresented: self.$bEnable) { () -> ActionSheet in
            ActionSheet(title: Text("🌀 ゾルタスクゼイアン"), message: Text("ゾルタスクゼイアンとは、Siriに対し質問をした際に返ってくる答えの中に登場する語句"), buttons: [
                .default(Text("Siriにきく")),
                .cancel(Text("怖いのでキャンセル"))])
        }
    }
}

ActionSheetのbuttonsに.default・.cancel・.destructiveが配列で設定できそれぞれにactionを追加できる。

.destructive()を使った場合文字に赤が設定される。

ActionSheet ボタン追加
ActionSheet ボタン追加

下のコードは、ActionSheetに複数のボタンを設定し、actionも追加した例です。

struct MessageDlg: View {
    @State var bEnable: Bool = false
    @State var c1: Color = Color.clear
    var body: some View {
        ZStack {
            c1
            Button("Button1", action: {
                self.bEnable = true
            } ).actionSheet(isPresented: self.$bEnable) { () -> ActionSheet in
                ActionSheet(title: Text("背景色"), message: Text("何色にしますか?"), buttons: [
                    .default(Text("黄"), action: { self.c1 = Color.yellow } ),
                    .destructive(Text("赤"), action: { self.c1 = Color.red } ),
                    .default(Text("緑"), action: { self.c1 = Color.green } ),
                    .cancel(Text("戻す"), action: { self.c1 = Color.clear } )])
            }
        }
    }
}

上のコードはZStackを使って背景色ColoractionSheetのボタンアクションで変更する例です。下絵のような動きです。

ActionSheetで背景色変更
ActionSheetで背景色を変更

コメントを残す

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

CAPTCHA


2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED