我有一个 UICollectionView
嵌套在 UITableViewCell
中:
Collection View 单元格内的数字会在不同的 View 中更新,因此当我返回到此屏幕时,我希望能够刷新 View 并且新数字反射(reflect)在它们的单元格中。我的 Collection View 中有一个名为 topUserModel
的模型,我用我的 firebase 数据库中的数据填充它。当我下拉刷新时,从我的主 TableView 中运行以下函数:
@objc func refreshView(refreshControl: UIRefreshControl) {
DispatchQueue.main.async {
//this is the row that the collection view is in
if let index = IndexPath(row: 1, section: 0) as? IndexPath {
if let cell = self.homeTableView.cellForRow(at: index) as? TopUserContainerViewController {
cell.userCollectionView.reloadData()
}
}
}
refreshControl.endRefreshing()
}
然后在 Collection View 触发中运行我的 awakeFromNib()
:
func fetchTopUsers() {
topUserModel.removeAll()
let queryRef = Database.database().reference().child("users").queryOrdered(byChild: "ranking").queryLimited(toLast: 10)
queryRef.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
let topUser = TopUser(dictionary: dictionary)
self.topUserModel.append(topUser)
}
DispatchQueue.main.async {
self.userCollectionView.reloadData()
}
})
}
请注意,我做的第一件事是从 topUserModel
中删除所有数据。在存储新数据并附加它之后(见上文),我可以将该代码块中的整数值打印到屏幕上,并将其显示为更新后的值。
然而,在我的 Collection View 中(见下文),如果我要在此处的任何时候打印出整数值(它称为 watchTime
),它仍然显示旧值,即使 topUserModel
已被清除并添加了新数据?:
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "topUserCell", for: indexPath) as! TopUsersViewController
if topUserModel.count > indexPath.row {
//image stuff redacted
Nuke.loadImage(
with: ImageRequest(url: url).processed(with: _ProgressiveBlurImageProcessor()),
options: options,
into: cell.topUserImage
)
cell.topUserName.text = topUserModel[indexPath.row].username
cell.topUserMinutes.text = "\(String(describing: topUserModel[indexPath.row].watchTime!))"
}
return cell
}
最佳答案
除了 cellForRowAt
之外,您不应该在任何地方调用 dequeueReusableCell
。
为了获取当前显示的单元格(如果有的话),您使用 cellForRowAt:
;如果该行当前不在屏幕上,这可能会返回 nil
。
获得单元格后,您可以重新加载它的数据并刷新其 Collection View 。
关于ios - 嵌套在 UITableViewCell 中的 UICollectionView 在收到新数据后不会使用 DispatchQueue 进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50730828/