【发布时间】:2018-03-26 13:06:09
【问题描述】:
在获取使用的数据后,它在viewDidLoad 中被调用。
经过一些打印调试后,如果没有更改数据,它看起来会调用所有适当的委托方法。如果有一些数据发生变化,cellForItemAt 不会被调用。
重新加载整个部分可以正常工作。但是给了我一个不需要的动画。之前尝试禁用 UIView 动画,并在重新加载部分后启用,但仍然给了我一点动画。
collectionView.reloadSections(IndexSet(integer: 0))
这是我目前的情况,使用 reloadData() 时
UICollectionViewController 是 TabBarController 的一部分。 我正在使用自定义 UICollectionViewCells。数据从 CoreData 加载。
第一次打开标签,它工作正常。 在另一个选项卡中更新收藏夹项目并返回到此 collectionView 后,它没有更新。但是,如果我选择另一个选项卡,然后返回到这个选项卡,它就会更新。
var favorites = [Item]()
override func viewWillAppear(_ animated: Bool) {
collectionView!.register(UINib.init(nibName: reuseIdentifier, bundle: nil), forCellWithReuseIdentifier: reuseIdentifier)
if let flowLayout = collectionView!.collectionViewLayout as? UICollectionViewFlowLayout {
flowLayout.estimatedItemSize = CGSize(width: 1,height: 1)
}
loadFavorites()
}
func loadFavorites() {
do {
print("Load Favorites")
let fetch: NSFetchRequest = Item.fetchRequest()
let predicate = NSPredicate(format: "favorite == %@", NSNumber(value: true))
fetch.predicate = predicate
favorites = try managedObjectContext.fetch(fetch)
if favorites.count > 0 {
print("Favorites count: \(favorites.count)")
notification?.removeFromSuperview()
} else {
showEmptyFavoritesNotification()
}
print("Reload CollectionView")
collectionView!.reloadData(
} catch {
print("Fetching Sections from Core Data failed")
}
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print("Get number of section, \(favorites.count)")
if favorites.count > 0 {
return favorites.count
} else {
return 0
}
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
print("Get cell")
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SubMenuCell
let menuItem = favorites[indexPath.row]
cell.title = menuItem.title
cell.subtitle = menuItem.subtitle
return cell
}
控制台打印/日志
启动应用程序,转到没有收藏夹的 CollectionView 选项卡:
Load Favorites
Get number of section, 0
Get number of section, 0
Reload CollectionView
Get number of section, 0
切换选项卡,添加 Item 对象并将其设置为 true,然后返回 CollectionView 选项卡:
Load Favorites
Favorites count: 1
Reload CollectionView
Get number of section, 1
The datamodel has 1 item, reloading CollectonView, cellForRowAtIndex not called?
选择另一个选项卡,随机选择哪个选项卡,然后返回 CollectionView 选项卡,不更改任何数据。
Load Favorites
Favorites count: 1
Reload CollectionView
Get number of section, 1
Get cell
现在我的项目显示在列表中。您可以从 Get Cell 中看到 cellForItemAt 也被调用。这最后两次日志记录之间没有任何变化,只是在选项卡上单击了一次后退/第四次。
忘了提,但这段代码在模拟器中运行良好。
在读取设备上它只是没有给我任何错误,只是没有显示单元格(或调用cellForItemAt)
【问题讨论】:
-
您能否更具体地说明什么不起作用,如果您已正确设置所有内容,那么在
collectionView上调用reloadData()不会为每个可见的调用cellForItemAtIndexPath项目(行)...
标签: ios swift uicollectionview