我不确定这是否可能,我环顾四周,在线检查,最后在这里发布这个问题,我想做的是,
我在 UITableView 中有 3 个部分,但只有当我的数据模型更新时第三部分才会出现
enum Section: Int {
case title, accounts, pending, total
}
在我目前拥有的 numberOfSections 中,
return (pendingDataModel != nil) ? 3 : 2
是否可以在枚举的计算属性中处理这个问题?就像基于上述条件添加和隐藏案例 pending
以便我只能使用 Section.total.rawValue
来获取我的部分的计数?
编辑: 我找到了这个答案,但这不是我想要的 Adding a case to an existing enum with a protocol
最佳答案
一个想法是使用结构体作为数据和 View Controller 之间的中介。这个结构体可以通过像tableview的单元格计数这样的方法来创建和使用;每次您的 View 需要知道其布局时,它都会根据是否存在待处理数据来构造自身。
enum Section: Int, CaseIterable {
case title, accounts, pending, total
}
struct SectionData {
var sections: [Section]
init(hasPendingData: Bool) {
if (hasPendingData) {
sections = Section.allCases
} else {
sections = [.title, .accounts]
}
}
}
class MyViewController: UIViewController {
var pendingModelData: Data?
func sectionCount() -> Int {
return SectionData(hasPendingData: pendingModelData != nil).sections.count
}
}
更进一步,您可以在pendingModelData 上使用didSet 来更新显示部分的 View 。
关于swift - 动态创建枚举案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59740581/