[英]SwiftUI - Dynamic list of buttons in ActionSheet
我需要在ActionSheet
中生成按鈕的動態列表。 假設我有一系列選項["Option1", "Option2"]
,我該如何實現?
.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()])
}
這是可能的解決方案。
現在actionSheet
替換為接受視圖構建器的confirmationDialog
對話框,所以現在它在內部是可行的,比如
.confirmationDialog("", isPresented: $showSheet) {
ForEach(currentOptions.indices, id: \.self) { i in
Button(currentOptions[i]) { self.option = i + 1 }
}
}
使用 Xcode 11.4 / iOS 13.4 測試
有幫手 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()])
}
然后你可以使用
.actionSheet(isPresented: self.$showSheet, content: {
// assuming you have `currentOptions` (or similar) property for dynamic
// options
self.generateActionSheet(options: self.currentOptions)
})
您可以通過類似於以下的方式來實現;
@State var flag: Bool = false
@State var options: [(String, () -> Void)] = [
("Option - 1", { print("option1 selected")}),
("Option - 2", { print("option2 selected")}),
("Option - 3", { print("option3 selected")})
]
var body: some View {
Button("Show action sheet") {
self.flag = true
}
.actionSheet(isPresented: self.$flag, content: {
var buttons: [ActionSheet.Button] = options.map {
ActionSheet.Button.default(Text($0.0), action: $0.1)
}
buttons.append(.cancel())
return ActionSheet(title: Text("Select an option"), buttons: buttons)
})
}
你可以試試這樣的
struct ContentView: View {
@State var showActionSheet: Bool = false
var titles: [String] = ["Option1", "Option2", "Option3"]
var buttonsArray: NSMutableArray = NSMutableArray()
init() {
loadArray()
}
var body: some View {
Button("Show Action Sheet") {
self.showActionSheet = true
}.actionSheet(isPresented: $showActionSheet) { () -> ActionSheet in
ActionSheet(title: Text("Some Action"),
message: Text("optional message"),
buttons: self.buttonsArray as! [ActionSheet.Button])
}
}
func loadArray() {
for i in 0..<self.titles.count {
let button: ActionSheet.Button = .default(Text(self.titles[i])) {
print(self.titles[i])
}
self.buttonsArray[i] = button
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.