swift - 动态创建枚举案例

标签 swift uitableview enums

我不确定这是否可能,我环顾四周,在线检查,最后在这里发布这个问题,我想做的是,

我在 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/

相关文章:

java - 编写接受/返回任何枚举的枚举常量的方法

c# - 在 C# 中创建枚举时出错 - "identifier expected"

ruby-on-rails - Ruby on Rails 全局 ActiveRecord::枚举

ios - 如何让图像出现在 Swift 的 UI PickerView 组件中?

swift - 删除的 tableviewcell 被最后一个单元格替换

ios - 如何以编程方式快速创建 uicollectionview(没有 Storyboard)

iphone - UIColor功能崩溃

ios - 加载图像时 asyncImageView 崩溃

ios - 将按钮放在屏幕的左下角

ios - 禁用自动布局后的问题