Swift 动态创建枚举案例
我不确定这是否可能,我环顾四周,上网查看,最后在这里发布了这个问题,我想做的是 UITableView中有3个部分,但第三部分仅在数据模型更新时显示Swift 动态创建枚举案例,swift,uitableview,enums,Swift,Uitableview,Enums,我不确定这是否可能,我环顾四周,上网查看,最后在这里发布了这个问题,我想做的是 UITableView中有3个部分,但第三部分仅在数据模型更新时显示 enum Section: Int { case title, accounts, pending, total } 在我目前拥有的部分中 return (pendingDataModel != nil) ? 3 : 2 是否可以在enum的computed属性中处理此问题?例如,基于上述条件添加和隐藏案例挂起,以便我只能使用Secti
enum Section: Int {
case title, accounts, pending, total
}
在我目前拥有的部分中
return (pendingDataModel != nil) ? 3 : 2
是否可以在enum的computed属性中处理此问题?例如,基于上述条件添加和隐藏案例
挂起
,以便我只能使用Section.total.rawValue
获取我的节的计数
编辑:
我找到了这个答案,但这不是我想要的一个想法是使用结构作为数据和视图控制器之间的中介。这个结构可以通过tableview的cell count这样的方法创建和使用;每次视图需要知道其布局时,它都会使用是否存在挂起数据来构造自己
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来更新视图显示部分。使用嵌套枚举的枚举可以是一种解决方案
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
pendingDataModel != nil ?
Section.Count.hasPendingRecords.rawValue : Section.Count.noPendingRecords.rawValue
}
Section.total.rawValue
是个坏主意,即使你做了你想要的。您需要的是节的总数。关于Section.total.rawValue
一点也不清楚,因此如果看到一些(似乎)任意的rawValue
被用于计数,那将是非常令人困惑的。假设您有某种FooModel
类型,以及用于显示它的FooTableViewDataSource
,这样的代码(用于确定节数)的适当位置是FooTableViewDataSource
上的computed属性中,它访问fooModel
并确定正确的节数。@我同意Section.total.rawValue
令人困惑,不是最佳做法,但您能否给出一个“FooTableViewDataSource上的computed属性,它访问fooModel并确定正确的节数”的示例?我没有时间编一个例子,但我是说你所做的基本上是正确的。FooTableViewDataSource
(符合UITableViewDataSource
)的目的是包装一段数据(您的fooModel:fooModel
)并使其适应表视图。这要求它计算重新呈现fooModel
所需的节数。正确的计算位置在FooTableViewDataSource
中。分区枚举的目的不是计算它。如果您的FooTableViewDataSource
变得太毛茸茸,那么提取一个单独的presenter
对象可能是值得的,它包含了在fooModel
中提取/派生各种面向用户的数据表示所需的助手方法。这太棒了!谢谢不客气,如果我能再帮点忙,请告诉我。
enum Section: Int {
case title, accounts, pending, total
enum Count: Int {
case hasPendingRecords = 3
case noPendingRecords = 2
}
}