正如您所提到的,NScollectionView
一次構建所有單元格。特別是如果在單元內有很多圖像會導致性能問題。這是我解決問題的方法。可能有更好的解決方案,但只要這對我來說工作得很好。 很長時間以來,我一直在用Instruments觀察代碼的性能,並沒有發現任何缺陷。
- (void)windowDidLoad {
//Here adding observer to NSCollectionView's scrollview to monitor bounds changes.
NSView *contentView = [scrollViewOfYourCollectionView contentView];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(boundDidChange:) name:NSViewBoundsDidChangeNotification object:contentView];
}
- (void)boundDidChange:(NSNotification *)notification
{
NSRect collectionViewVisibleRect = yourCollectionView.visibleRect;
//collectionViewVisibleRect.size.height += 300; //If you want some preloading for lower cells...
for (int i = 0; i < yourDataSourceArray.count; i++) {
NSCollectionItem *item = [yourCollectionView itemAtIndex:i];
if (NSPointInRect(NSMakePoint(item.view.frame.origin.x, item.view.frame.origin.y), collectionViewVisibleRect) == YES)
{
if (item.imageView.image == nil) {
dispatch_async(dispatch_get_main_queue(), ^{
//Fill your cells.
//to showing/downloading images I am using SDWebImage.
});
}
}
}
}
謝謝,明天我會試試並報告回來!你覺得你需要做特別的事情來清理那些看不見的細胞嗎? – user441669
這是我原來的計劃,但是一旦我看到它不影響我離開它的表現。如果你想清理它們,你可以將imageView圖像設置爲零,如果單元格不在可見矩形中。 – mohacs
非常適合我,謝謝。 – user441669