我有一个动态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
}
型
2条答案
按热度按时间r8uurelv1#
这不是SwiftUI的问题,而是数据过滤的问题。不要循环遍历在此视图中没有业务显示的状态。😉
您可以使用单独的
var
,它只提供bucketList中的状态-而不是以这种未经过滤的方式使用.allCases
。现在,在你的代码 (或者更好的是,在你的viewModel或presenter) 中,你可以这样做:
字符串
然后使用它而不是
USStates.allCases
来迭代List
。型
wtlkbnrh2#
你可以像下面这样声明一个计算变量
displaySections
:字符串
然后展示它。
型