最近在寫一個類似于京東商城分類的頁面,不一樣的是,我們在選擇一個分類下拉帥心數(shù)據(jù)之后,還能隨時切換到按照銷量,價格排序刷新數(shù)據(jù)。
在這個過程中,遇到了一個很煩人的問題,來回滑動刷新數(shù)據(jù)的同時,點擊切換至銷量等其他分類就會崩潰,崩潰原因就是
*** Assertion failure in -[UICollectionViewData validateLayoutInRect:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit/UIKit-3600.5.2/UICollectionViewData.m:433
簡單的說就是,collectionview的布局還沒更新,你頁面就刷新了,肯定會崩潰。如果頁面滿滿的滑動就幾乎不會出現(xiàn)崩潰,但是只要測試滑動的快一些,必崩。
所以就在網(wǎng)上開始了無邊無際的搜索答案,然而跟我類似的情況的真的很少?。∽詈蠼^望之際,看到了一個技術友人的提示:重寫UICollectionViewFlowLayout的prepareLayout方法。
就是我們需要在加載collecview之前清除之前所有的布局屬性,具體內(nèi)容請參考胰以下代碼:
@interface myCollectionViewLayout ()
{
?NSMutableArray * _attributeArray;
}
@end
@implementation?myCollectionViewLayout
-(void)prepareLayout
{
?_attributeArray = [NSMutableArray array];?
?[super prepareLayout];?
?NSInteger count = [self.collectionView numberOfItemsInSection:0];?
for (int i =0; i<count;i++
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
? ? ? ? UICollectionViewLayoutAttributes * attrs = [self layoutAttributesForItemAtIndexPath:indexPath];
[_attributeArray addObject:attrs];
}
}
-(NSArray<UICollectionViewLayoutAttributes> *)layoutAttributesForElementsInRect:(CGRect)rect
{
return _attributeArray;
}
@end
這便是.m文件里的所有內(nèi)容了,.h文件里面沒有東西。
如果你遇到了類似的問題,可以參考一下這種解決方式。
我修改之后,便沒有遇到崩潰。
與君共勉。