首页 > 解决方案 > UICollectionView 如何更新单元格?

问题描述

我正在构建一个跟踪包裹的应用程序。UICollectionView 中的每个单元格都包含包裹的名称和包裹的交付状态。我的集合视图的数据源是一个项目数组。

Item 类看起来像这样:

class Item {
    var name: String
    var carrier: String 
    var trackingNumber: String 
    var status: String //obtained via API get request at some point after initialization 
}

我想实现两个功能:添加项目的能力(并随后触发所有项目的更新)以及仅触发所有项目的更新的能力。这是我的 ViewController 基本上的样子:

class PackagesController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
    var items: [Item]? 
    override func viewDidLoad() {super.viewDidLoad()}
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return items.count
    }
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //return an item cell 

        //Is this where I should make the API request? 

    }
}

我的问题是:

  1. 我应该在哪里发出 API 请求(以获得最大效率)?

  2. 如何根据用户的请求更新所有项目的信息(不确定循环通过项目数组是否会导致集合视图重新加载)?

  3. 我的代码当前的结构方式是否存在固有问题,或者是否有更好的方法来组织我的代码以达到预期目的?

标签: iosswiftapiuicollectionviewuicollectionviewcell

解决方案


到目前为止,您编写的代码看起来大部分都还可以。

我建议的一些更改:

  • Item应该是一个结构,而不是一个类,并且它的成员应该是常量(let),除非你有非常好的和具体的原因。
  • “在初始化后的某个时候通过 API 获取请求获得”听起来应该是 Optional ( String?)

这是我应该发出 API 请求的地方吗?

不,永远不要做网络请求或任何复杂的cellForItemAt. 只需从您的数据源(即您的项目数组)中获取适当的记录,然后用它填充单元格。


func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    // get a cell
    let cell = collectionView.dequeueResuableCell(withIdentifier: "yourCellIdentifier", indexPath: indexPath) as! YourCellClass
    // get the data
    let item = self.items[indexPath.row]
    // populate the cell with the data
    cell.setup(with: data) // you need to implement this in your cell

    return cell
}

如何根据用户的要求更新所有项目的信息

进行相应的网络请求/计算或任何必要的操作,一旦获得结果,覆盖您的items数组并调用reloadData()CollectionView。把它放在一个你可以调用的方法中,例如作为一个按钮点击的动作,当然当你的集合视图最初显示时。


推荐阅读