我有一个 CollectionView 显示有关用户的一些信息。其中一项是用户头像(100x100 png),它是从我们的网络服务器加载的。问题是,在我看来,当单元格超出屏幕区域时,视图会重新加载单元格。每次我滚动页面时,当完全位于屏幕区域之外的单元格进入屏幕时,它都会滞后一点。在 wifi 上这不是一个真正的大问题,但在 3g 上这真的很慢,而且它会消耗带宽。总的来说,为我的应用处理这样的数据是很糟糕的。我想加载一次数据并显示它,而不是在用户滚动页面时有数百个网络请求。有什么方法可以加载一次单元格,然后在我手动更新它们之前将它们保持原样?我还没有进行任何更新,这是我当前的代码:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return numContacts;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"Cell" forIndexPath:indexPath];
UILabel *contactName = (UILabel *)[cell viewWithTag:1];
char *text = contactArray[indexPath.row].name;
contactName.text = [NSString stringWithCString:text encoding:NSASCIIStringEncoding];
NSData * presence = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"offline" ofType:@"png"]];
UIImageView *presenceView = (UIImageView *)[cell viewWithTag:2];
presenceView.image = [UIImage imageWithData: presence];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"myWebServer",text]];
NSData * avatar = [[NSData alloc] initWithContentsOfURL:url];
UIImageView *avatarView = (UIImageView *)[cell viewWithTag:3];
avatarView.image = [UIImage imageWithData: avatar];
NSData *placeholder = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"avatar_unknown" ofType:@"png"]];
[avatarView setImageWithURLRequest:[NSURLRequest requestWithURL:url] placeholderImage:[UIImage imageWithData:placeholder] success:nil failure:nil];
return cell;
}