Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - Dynamic list of buttons in ActionSheet

I need to generate a dynamic list of buttons in an ActionSheet. Say I have an array of options ["Option1", "Option2"], how can I achieve this?

.actionSheet(isPresented: self.$showSheet, content: {
        ActionSheet(title: Text("Select an option"), buttons: [
            .default(Text("Option1")){self.option = 1},
            .default(Text("Option2")){self.option = 2},
            .default(Text("Option3")){self.option = 3},
            .default(Text("Option4")){self.option = 4},
            .cancel()])
    }
like image 423
Ken Chung Avatar asked Oct 21 '25 15:10

Ken Chung


1 Answers

Here is possible solution.

Update: Xcode 13.3 / iOS 15.4

Now actionSheet is replaced with confirmationDialog which accepts view builder, so now it is just doable inside, like

.confirmationDialog("", isPresented: $showSheet) {
    ForEach(currentOptions.indices, id: \.self) { i in
        Button(currentOptions[i]) { self.option = i + 1 }
    }
}

Deprecated:

Tested with Xcode 11.4 / iOS 13.4

having helper function

func generateActionSheet(options: [String]) -> ActionSheet {
    let buttons = options.enumerated().map { i, option in
        Alert.Button.default(Text(option), action: { self.option = i + 1 } )
    }
    return ActionSheet(title: Text("Select an option"), 
               buttons: buttons + [Alert.Button.cancel()])
}

you then can use

.actionSheet(isPresented: self.$showSheet, content: {
   // assuming you have `currentOptions` (or similar) property for dynamic
   // options
   self.generateActionSheet(options: self.currentOptions)
})
like image 190
Asperi Avatar answered Oct 23 '25 07:10

Asperi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!