【问题标题】:Best Datasource Configuration for UITableView with Sections带有部分的 UITableView 的最佳数据源配置
【发布时间】:2017-07-01 17:29:46
【问题描述】:

我有一个数组

    secInfArr = []
    let secInf1 = SecInfObj.init()
    secInf1.selected = true
    secInf1.itemName = "item1"
    secInf1.sectionName = "section3"
    secInfArr.append(secInf1)

    let secInf2 = SecInfObj.init()
    secInf2.selected = true
    secInf2.itemName = "item1"
    secInf2.sectionName = "section1"
    secInfArr.append(sectionInfo2)

    let secInf3 = SecInfObj.init()
    secInf3.selected = true
    secInf3.itemName = "item1"
    secInf3.sectionName = "section1"
    secInfArr.append(secInf3)

    let secInf4 = SecInfObj.init()
    secInf4.selected = false
    secInf4.itemName = "item1"
    secInf4.sectionName = "section2"
    secInfArr.append(secInf4)

我想创建一个tableView,其中所有这些内容都按sectionName 属性分组,并且该部分中的所有itemNames 都按字母顺序排序。

到目前为止,我正在做我认为效率低下的事情。我正在对数组中的sectionName 属性执行Distinct 操作,然后使用它来命名部分并计算它们。之后,在CellForRowAtIndexPath 方法中,我只需使用sectionName 过滤数组,然后添加单元格。

我也想过使用NSFetchedResultsController,但我认为这不是一个好主意,因为数据本质上不是持久的,因此不需要采用managedObject 形式。

在这种情况下,为分组表视图构建数据的理想方式是什么?

【问题讨论】:

    标签: ios swift uitableview cocoa-touch


    【解决方案1】:

    我推荐一个面向对象的解决方案,例如具有name 属性和items 数组的结构,这里是通用形式。

    struct Section<T> {
    
        let name : String
        var items = [T]()
    
    }
    

    如果items 数组经常发生突变,请使用class 而不是struct 来利用引用语义。

    填充数据源时,将SecInfObj 对象分配给适当的Section 实例。

    项目可以轻松排序,您可以声明数据源

    var data = [Section<SecInfObj>]()
    

    numberOfRows返回

    return data[section].items.count
    

    您通过索引路径获取部分

    let section = data[indexPath.section]
    

    然后是带有

    的项目
    let items = section.items[indexPath.row]
    

    【讨论】:

    • 感谢您的回复,瓦迪安。基本上,我无法控制数据,我以我从 Web 服务描述的形式接收它。在没有嵌套 for 循环的情况下,将它们转换为上述结构的最有效方法是什么?
    【解决方案2】:

    我建议根据部分将它们分别制作成不同的数组。在数据源中调用要容易得多,尤其是对于 numberOfRowsInSectioncellForRowAt 方法。 UITableView 也很容易获取每个单元格的数据,因为它通过索引直接访问数组。

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    
        if section == 0 {
            return items0.count
        }
        else if section == 1 {
            return items1.count
        }
        return 0
    }
    

    或者也可以类似如下。如果全部分别进入items[0] ... items [n]

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

    【讨论】:

      猜你喜欢
      • 2014-10-15
      • 1970-01-01
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多