ios - 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?
}
}
我的问题是:
我应该在哪里发出 API 请求(以获得最大效率)?
如何根据用户的请求更新所有项目的信息(不确定循环通过项目数组是否会导致集合视图重新加载)?
我的代码当前的结构方式是否存在固有问题,或者是否有更好的方法来组织我的代码以达到预期目的?
解决方案
到目前为止,您编写的代码看起来大部分都还可以。
我建议的一些更改:
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。把它放在一个你可以调用的方法中,例如作为一个按钮点击的动作,当然当你的集合视图最初显示时。
推荐阅读
- node.js - 我尝试从 multipart api 上传文件和文本数据,但即使我使用 multer 也无法获取文件
- c - 使用 calloc() 存储地址
- apache-spark - 在同一个 Spark 会话中运行多个 Spark Kafka 结构化流查询会增加偏移量但显示 numInputRows 0
- swift - 从 swift 背景到前景时无法调用 ViewWillAppear
- pyspark - 在 pySpark 中过滤有关薪水的数据
- android - 使用 AlertDialog 时,我无法更新和删除 Firebase 数据库中的数据
- ios - iOS 迅捷 | 没有得到最新的变量值
- r - 使用 ggmap 和 googleAuthR 在 R 图中使用地图的注册
- c - 为什么添加链接器标志 `-save-temps` 可以解决 clang-8 错误:“无法制作临时文件”?
- wpf - WPF RichTextBox中修改后如何保持Run一起