iOS Swift 动态更新 UICollectionView
iOS Swift update UICollectionView dynamically
好吧,我有一个非常烦人的动态更新 CollectionView 的问题。我总是收到错误消息:"UICollectionView received layout attributes for a cell with an index que path does not exist"
我做了一个显示水果的基本设计,添加了一个仅显示苹果的按钮,当我单击此按钮时,抓取只有苹果的内容并发送更新 CollectionView,我看到了这个错误...
这里是动态更新我的 CollectionView 的方法:
@IBAction func showOnlyApple(sender: AnyObject) {
var justApple = [FruitsObject]()
for item in self.fruitsCollection{
if (item.name! == "Maça") {
justApple.append(item)
}
}
self.fruits = justApple
self.uiCollectionView.reloadData()
}
如果有人想看错误,这里是项目:
https://github.com/bkawakami/CollectionViewFruits
只需构建项目并单击按钮,"Só Maçã"
有人通过或知道如何解决这个错误?
谢谢!
在您的 CardsLayout
class 中,您正在遍历一个从未更新的 cache
变量以设置布局属性。您看到此错误是因为您返回的单元格布局属性不再存在于您的数据源中,但仍存在于您的 cache
中。解决此问题的一种方法是将 layoutAttributesForElementsInRect(rect: CGRect)
更改为以下内容:
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
// Clear the cache
cache.removeAll()
// Call prepare layout to repopulate the cache based on the new number of items
prepareLayout()
for attributes in cache {
if CGRectIntersectsRect(attributes.frame, rect ) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
但是,这首先违背了 cache
的目的 - 既然您了解了这个问题,您应该能够相应地重新设计 CardsLayout
class。
好吧,我有一个非常烦人的动态更新 CollectionView 的问题。我总是收到错误消息:"UICollectionView received layout attributes for a cell with an index que path does not exist"
我做了一个显示水果的基本设计,添加了一个仅显示苹果的按钮,当我单击此按钮时,抓取只有苹果的内容并发送更新 CollectionView,我看到了这个错误...
这里是动态更新我的 CollectionView 的方法:
@IBAction func showOnlyApple(sender: AnyObject) {
var justApple = [FruitsObject]()
for item in self.fruitsCollection{
if (item.name! == "Maça") {
justApple.append(item)
}
}
self.fruits = justApple
self.uiCollectionView.reloadData()
}
如果有人想看错误,这里是项目: https://github.com/bkawakami/CollectionViewFruits
只需构建项目并单击按钮,"Só Maçã"
有人通过或知道如何解决这个错误?
谢谢!
在您的 CardsLayout
class 中,您正在遍历一个从未更新的 cache
变量以设置布局属性。您看到此错误是因为您返回的单元格布局属性不再存在于您的数据源中,但仍存在于您的 cache
中。解决此问题的一种方法是将 layoutAttributesForElementsInRect(rect: CGRect)
更改为以下内容:
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
// Clear the cache
cache.removeAll()
// Call prepare layout to repopulate the cache based on the new number of items
prepareLayout()
for attributes in cache {
if CGRectIntersectsRect(attributes.frame, rect ) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
但是,这首先违背了 cache
的目的 - 既然您了解了这个问题,您应该能够相应地重新设计 CardsLayout
class。