【问题标题】:Swift Collectionview Datasource and SectionsSwift Collectionview 数据源和部分
【发布时间】:2017-09-10 14:13:44
【问题描述】:

所以,我之前已经问过这方面的问题,但我想我需要更多帮助,因为我无处可去。

我的应用小结:

现在状态: 用户可以在一个视图控制器上获得设备列表,并可以在开始屏幕上查看他们想要查看的详细信息。 设备的 ID 存储在一个数组中,如下所示:

devArray["device1", "device2",..].

此数组存储在UserDefaults 中。从URLSession 拉取服务器数据。

然后所有的都被拉到一起

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let colcel = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! MyCollectionViewCell
    let id = devArray[indexPath.row]
    let devListItem = self.devicesFromTheServer.filter { ($0["id"] as! String) == id }[0]

设备显示在没有任何部分的 CollectionView 中,用户可以重新排列单元格。这效果很好。

我现在的意图是提供将设备分组的功能。 我想了一个字典,看起来像这样:

dict["device1":"sectionA", "device2":"sectionA", "device3":"SectionB"]

但我无法理解如何以此构建 Collectionview,而且我不确定我的字典形式是否正确...

你能帮帮我吗?

【问题讨论】:

    标签: swift uicollectionview


    【解决方案1】:

    您可以在此处采用几种方法。第一个是二维数组,它是一个包含每个部分的设备数组的数组。另一种方法更具可扩展性,允许您仅使用设备名称对数据进行建模。

    第二种方法是我在下面介绍的。

    你需要的是这样的:

    /// Defines a section in data source
    struct Section {
    
       // MARK: - Properties
    
       /// The title of the section
       let title: String
    
       /// The devices in the section
       var devices: [String]
    }
    

    然后在您的视图控制器中定义一个存储部分的数组,如下所示:

    var dataSource = [Section(title: "Section 1", devices: ["Device 1"]), Section(title: "Section 2", devices: ["Device 2","Device 3"])]
    

    您可以使用您已有的一些逻辑,通过将设备附加到单独函数中的每个部分来自定义此设置。只是为了这个答案,我已经让它变得更简单了。

    然后添加这些集合视图数据源和委托方法:

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource[section].devices.count
      }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
      return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! MyCollectionViewCell
      cell.textLabel?.text = dataSource[indexPath.section].devices[indexPath.row]
      return cell
    }
    

    【讨论】:

    • 感谢您的回复。我没有得到的是是否应该更改我的 dict 或如何将其放入结构或数组中?
    • 好吧,因为该部分是您定义的,您必须手动将设备添加到Section(title: "Section 1", devices: [<add devices here>] 中的设备阵列。这将是您可以将其包装在函数中以使其更清洁的东西。我根本没有用过字典,所以我认为你不应该在这个应用程序中使用它。
    • 是的,它把我引向了正确的方向。谢谢你的帮助
    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 2019-04-09
    • 2018-11-27
    • 2020-08-31
    • 2019-03-11
    • 1970-01-01
    相关资源
    最近更新 更多