2014-12-03 41 views
0

我UICollectionView細胞的數量有一個非零contentInsetUICollectionView - 如何提高被分配

self.collectionView.contentInset = UIEdgeInsetsMake(self.mainNavigation.bounds.size.height, 0, 0, 0); 

主導航是一個透明的導航欄 - 一旦用戶向下滾動,的CollectionView可以部分地通過主導航中可以看出。更多的單元格被初始化,因爲collectionView的「屏幕上」框架增加了(這些新的單元格沒有出列)。

單元的初始化非常昂貴,導致UI滯後。

我需要的是collectionView最初將更多的單元格加載到內存中,以便初始滾動更平滑。

如何增加最初加載的單元格數量?

回答

0

我不認爲你需要加載更多的細胞,因爲這是自然的行爲。如果您的滾動不順暢,也許是因爲您沒有正確加載單元格中的圖像。

您必須申請lazy loading pattern。例如,你可以這樣做(假設你已經設置了NSMutableDictionary* imageDic = [[NSMutableDictionary alloc] init];,你的細胞擁有財產@property(nonatomic, retain) UIImageView *imageView;,並且您使用AFNetworking

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView_ cellForItemAtIndexPath:(NSIndexPath *)indexPath{ 

UICollectionViewCell *cell = [collectionView_ dequeueReusableCellWithReuseIdentifier:@"identifier" forIndexPath:indexPath]; 

NSString* cellKey = [NSString stringWithFormat:@"%d_%d", indexPath.section, indexPath.row]; 
NSString* imgName = [cellKey stringByAppendingPathExtension:@"jpg"]; 
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]; 
NSString* imagePath = [documentsDirectory stringByAppendingPathComponent:imgName]; 

BOOL isDirectory = NO; 
NSFileManager* fm = [NSFileManager defaultManager]; 

// set image with image in cache (it will be fast!) 
if ([imageDic objectForKey:cellKey]) 
{ 
    UIImage *img = [imageDic objectForKey:cellKey]; 
    cell.imageView.image = img; 
} 
// set image with image saved in document directory and put it in cache 
else if ([fm fileExistsAtPath:imagePath isDirectory:&isDirectory]) 
{ 
    UIImage *img = [UIImage imageWithContentsOfFile:imagePath]; 
    cell.imageView.image = img; 
    [imageDic setObject:img forKey:cellKey]; 
} 
// download image at imageURL, save it and put it in cache too. Until then set image with a placeholder 
else 
{ 
    __weak UICollectionViewCell* weakCell = cell; 
    [cell.imageView setImageWithURLRequest:[NSURLRequest requestWithURL:imageURL] placeholderImage:[UIImage imageNamed:@"placeholder"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) { 
     weakCell.imageView.image = image; 
     [weakCell setNeedsLayout]; 

     [imageDic setObject:img forKey:cellKey]; 
     [UIImageJPEGRepresentation(img, 1.f) writeToFile:imagePath atomically:YES]; 
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) { 
     NSLog(@"failed to dl image"); 
    }]; 
} 

return cell; 
} 
0

有沒有辦法做到這一點。

你可以做的是:

  1. 優化細胞代碼和初始化去除沉重的部分,可能推遲某些操作,直到滾動停止。

  2. 使用純色背景進行子視圖併爲view.opaque設置合適的值。滾動時,它可以提高性能。這是你可以在模擬器中打開「Color Blended Layers」選項打開的東西。你會看到以綠色和紅色呈現的命中和失誤。

  3. 如果您使用自定義CALayers,請嘗試光柵化時/如果它們是靜態的。

  4. 緩存數據,如果委託在返回單元格之前執行繁重的操作。