【问题标题】:How does UICollectionView update the cells?UICollectionView 如何更新单元格?
【发布时间】:2020-05-01 17:50:08
【问题描述】:

我正在构建一个跟踪包裹的应用程序。 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. 我的代码当前的结构方式是否存在固有问题,或者是否有更好的方法来组织我的代码以达到预期目的?

【问题讨论】:

    标签: ios swift api uicollectionview uicollectionviewcell


    【解决方案1】:

    到目前为止,您编写的代码看起来基本没问题。

    我建议的一些更改:

    • Item 应该是一个结构,而不是一个类,并且它的成员应该是常量 (let),除非你有非常好的和具体的理由。
    • “在初始化后的某个时间点通过 API 获取请求获得”听起来应该是可选的 (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 数组并在 CollectionView 上调用 reloadData()。把它放在一个你可以调用的方法中,例如作为一个按钮点击的动作,当然还有当你的集合视图最初显示时。

    【讨论】:

      猜你喜欢
      • 2013-12-16
      • 2020-02-06
      • 1970-01-01
      • 2014-12-03
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多