在 SwiftUI 列表中选择多个项目 [英] Select Multiple Items in SwiftUI List

查看:33
本文介绍了在 SwiftUI 列表中选择多个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 UIKit 中,您可以使用

下面是我写的代码:

struct MultipleSelectionList: View {@State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]@State var 选择:[String] = []var主体:一些视图{列表 {ForEach(self.items, id: \.self) { item inMultipleSelectionRow(title: item, isSelected: self.selections.contains(item)) {如果 self.selections.contains(item) {self.selections.removeAll(where: { $0 == item })}别的 {self.selections.append(item)}}}}}}

struct MultipleSelectionRow: View {变量名称:字符串var isSelected: Boolvar 动作:() ->空白var主体:一些视图{按钮(动作:self.action){堆栈{文字(self.title)如果 self.isSelected {垫片()图像(系统名称:复选标记")}}}}}

In UIKit you can select multiple rows of a UITableView by using allowsMultipleSelection - can this be done with the List in SwiftUI?

解决方案

The only way to get multiple selection in SwiftUI right now is by using EditButton. However, that's not the only instance you might want to use multiple selection, and it would probably confuse users if you used EditButton multiple selection when you're not actually trying to edit anything.

I assume what you're really looking for is something like this:

Below is the code I wrote to create this:

struct MultipleSelectionList: View {
    @State var items: [String] = ["Apples", "Oranges", "Bananas", "Pears", "Mangos", "Grapefruit"]
    @State var selections: [String] = []

    var body: some View {
        List {
            ForEach(self.items, id: \.self) { item in
                MultipleSelectionRow(title: item, isSelected: self.selections.contains(item)) {
                    if self.selections.contains(item) {
                        self.selections.removeAll(where: { $0 == item })
                    }
                    else {
                        self.selections.append(item)
                    }
                }
            }
        }
    }
}

struct MultipleSelectionRow: View {
    var title: String
    var isSelected: Bool
    var action: () -> Void

    var body: some View {
        Button(action: self.action) {
            HStack {
                Text(self.title)
                if self.isSelected {
                    Spacer()
                    Image(systemName: "checkmark")
                }
            }
        }
    }
}

这篇关于在 SwiftUI 列表中选择多个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆