SwiftUI-ActionSheet中的按钮动态列表

时间:2020-05-26 08:06:08

标签: swiftui swiftui-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()])
    }

3 个答案:

答案 0 :(得分:3)

这是可能的解决方案。使用Xcode 11.4 / iOS 13.4进行了测试

具有辅助功能

print(W)
# array([18.56711151,  4.51542094])

print(X)
# [[1.    6.575]
#  [1.    6.421]
#  [1.    7.185]
#  ...
#  [1.    6.976]
#  [1.    6.794]
#  [1.    6.03 ]]

yP = W @ X.T
yP_ X @ W 
yP == yP_
#True

然后您可以使用

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()])
}

答案 1 :(得分:0)

您可以通过以下类似方式来实现;

@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)
    })
}

答案 2 :(得分:0)

您可以尝试类似

    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
            } 
        }
    }