ios - 在 UITableView 的部分中填充行的最佳方法?

标签 ios swift uitableview dictionary

我正在构建一个应用程序,其中我在 UITableView 中有几个部分。我目前的解决方案是将我的数据收集在字典中,然后为每个部分选择一个键。有更好的解决方案吗?

最佳答案

其中一个好方法 - 直接模型映射,尤其适用于快速枚举。 例如,您有 2 个不同的部分,其中包含 3 种不同类型的行。您的枚举和 ViewController 代码将如下所示:

enum TableViewSectionTypes {
    case SectionOne
    case SectionTwo
}

enum TableViewRowTypes {
    case RawTypeOne
    case RawTypeTwo
    case RawTypeThreeWithAssociatedModel(ModelForRowTypeNumberThree)
}

struct ModelForRowTypeNumberThree {
    let paramOne: String
    let paramTwo: UIImage
    let paramThree: String
    let paramFour: NSData
}

struct TableViewSection {
    let type: TableViewSectionTypes
    let raws: [TableViewRowTypes]
}

class ViewController: UIViewController, UITableViewDataSource {

    var sections = [TableViewSection]()

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].raws.count
    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let raw = sections[indexPath.section].raws[indexPath.row]
        switch raw {
        case .RawTypeOne:
            // Here return cell of first type
        case .RawTypeTwo:
            // There return cell of second type
        case .RawTypeThreeWithAssociatedModel(let modelForRawTypeThree):
            // And finally here you can use your model and bind it to your cell and return it
        }
    }
}

有什么好处?强大的类型化、显式建模和对各种单元格类型的显式处理。在这种情况下,您唯一需要做的简单事情就是将您的数据解析为枚举和结构,就像您为字典所做的那样。

关于ios - 在 UITableView 的部分中填充行的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143920/

相关文章:

ios - 下载 Xcode 4.2 文档以进行离线安装

swift - ascii to string swift 3 问题

ios - 自动布局约束警告 “Will attempt to recover by breaking constraint”

ios - UIAlertView 不打开 url?

ios - 带有自定义 UIToolbar xib 的 Storyboard 中的 UINavigationController 失败

ios - Xcode Instrument 中 SCNNodes 上 SCNAudioPlayer 的持久化

ios - 删除行时 SwiftUI ForEach 索引超出范围错误

swift - 使用 colorBlendFactor 更改 Sprite 的颜色

ios - 选择时向表格单元格添加滑动 View

ios - 在 TableView Controller 中的 TableView 上添加模糊 View