SwiftUI - ActionSheet 中的动态按钮?

Kyl*_*ley 2 ios swift swiftui

我正在尝试获取我的数组sizes(可以有不同的值)。我正在尝试循环遍历数组并.defaultActionSheet.

这是代码:

var sizes = ["S", "M", "L"]

var body: some View {
  Button( [...] )
  .actionSheet(isPresented: $showingActionSheet, content: {
    ActionSheet(title: Text("Select size..."), buttons: [
      ForEach(0 ..< sizes.count) { index in
        buttons.default(Text(sizes[index]) { print(sizes[index]) })
      }
    ])
  })
}
Run Code Online (Sandbox Code Playgroud)

显然,这不起作用,因为您无法在数组ForEach内部执行buttons。我将如何动态生成这些按钮及其功能?谢谢你!

Swe*_*per 6

ActionSheet接受一个数组作为其参数,因此您可以将map数组sizes转换为以下数组ActionSheet.Button

ActionSheet(title: Text("Select size..."), buttons:
    sizes.map { size in 
        .default(Text(size)) { print(size) } 
    }
)
Run Code Online (Sandbox Code Playgroud)

  • @lenny 例如,您可以使用“+”将其添加到数组的末尾:“sizes.map { ... } + .cancel()”。 (2认同)