ios 在SwiftUI中动态隐藏列表的空部分

aij0ehis  于 9个月前  发布在  iOS
关注(0)|答案(2)|浏览(145)

我有一个动态SwiftUI List,它使用状态枚举来填充。然后它在我的数据字典中循环,寻找状态匹配来显示数据。所有这些都很完美。我想做的是隐藏那些空的状态。
有问题的代码部分是:

@State private var bucketList: [BucketListItems] = []
...
List {
    ForEach(USStates.allCases) { states in
        Section {
            ForEach (bucketList) { item in
                if (item.state == states.abrev) {
                    NavigationLink(destination: ItemDetails(blItem: item.recordID)) {
                        Label(item.name, systemImage: item.monogram)
                                    .frame(height: 50)
                            .foregroundColor(item.completedate=="0000-00-00" ? .white : .red)
                    }
                }
            }
        } header: {
            Text(states.rawValue)
        }
    }
}

字符串
当一个州没有匹配项时,我希望整个部分都被隐藏起来。
一些额外的相关代码:

struct BucketListItems: Encodable, Decodable, Identifiable, Hashable {
    let id = UUID()
    var recordID: Int
    var url: String
    var user: Int
    var name: String
    var category: String
    var state: String
    var latitude: String
    var longitude: String
    var description: String
    var completedate: String
}

r8uurelv

r8uurelv1#

这不是SwiftUI的问题,而是数据过滤的问题。不要循环遍历在此视图中没有业务显示的状态。😉
您可以使用单独的var,它只提供bucketList中的状态-而不是以这种未经过滤的方式使用.allCases
现在,在你的代码 (或者更好的是,在你的viewModel或presenter) 中,你可以这样做:

var filteredStates: [USStates] {
    USStates.allCases.filter { state in
        bucketList.contains(state)
        # note: maybe you need to compare `abbrev` here- I see from your code they are likely different types.
    }
}

字符串
然后使用它而不是USStates.allCases来迭代List

List {
    ForEach(filteredStates) { states in /* ... */ }
    /** etc... **/

}

wtlkbnrh

wtlkbnrh2#

你可以像下面这样声明一个计算变量displaySections

// <your states enum cases here>
var sections: [String] = ["Section 1", "Section 2", "Section 4"]

// <Your bucket list here> 
var list = PremiumKeyFeatures.list

var displaySections: [String] {
    sections.filter { list.map { $0.section }.contains($0) }
    // apply filter and remove empty sections accordingly
}

字符串
然后展示它。

var body: some View {
    List {
        ForEach(displaySections, id: \.self) { title in
            Section {
                ForEach (list) { item in
                    if title == item.section {
                        Text(item.title)
                    }
                }
            } header: {
                Text(title)
            }
        }
    }

相关问题