【SwiftUI】複数ActionSheetの利用


何をやるのか?

SwiftUIで実装する一つのViewに対して、ActionSheetを複数実装すると最後に書いたものだけが適応され、それ以外のActionSheetは無効扱いになります。
そのため、ここでは複数のActionSheetの実装方法を備忘録として残しておきます。

// 無効になる
.actionSheet(isPresented: self.$showActionSheet1) {
                ActionSheet(
                    title: Text("Title1"),
                    message: Text("Message1"),
                    buttons: [
                        .default(Text("Button1"),
                        action: {
                            print("done1")
                        }),
                        .default(Text("Button 2"),
                        action: {
                            print("done2")
                        })
                    ])
            }
// 以下だけ有効
.actionSheet(isPresented: self.$showActionSheet2) {
                ActionSheet(
                    title: Text("Title2"),
                    message: Text("Message2"),
                    buttons: [
                        .default(Text("Button1"),
                        action: {
                            print("done1")
                        }),
                        .default(Text("Button2"),
                        action: {
                            print("done2")
                        })
                    ])
            }

解決策

以下のように分岐処理で任意のActionSheetを返すだけでいいみたいでした。

@State var showActionSheet = false
@State var optionsMenu: OptionsMenu = .action1

enum OptionsMenu { case action1, action2 }

///////////////////////////////////////////////////////////////

.actionSheet(isPresented: $showActionSheet) {
    if self.optionsMenu == .action1 {
        return ActionSheet(title: Text("Action1"), buttons: [
            .default(Text("ButtonTitle")) {
                print("tapped Button")
            }
            .destructive(Text("Close"))
        ])
    } else {
        return ActionSheet(title: Text("Action2"), buttons: [
            .default(Text("ButtonTitle2")) {
                print("tapped Button2")
            },
            .default(Text("ButtonTitle3")) {
                print("tapped Button3")
            },
            .destructive(Text("Close"))
        ])
    }
}

参考