任何人都可以帮助我如何显示事件指示器,直到 UICollection 单元格的图像在后端下载。
在我的代码中,事件指示器仅显示最后一个单元格。不知道我在哪里犯了错误
这是我的代码:
- (collectionCell *)collectionView:(UICollectionView *)collectionView
cellForItemAtIndexPath:(NSIndexPath *)indexPath{
[self.menuCollectionView registerNib:[UINib nibWithNibName:@"collectionCell"
bundle:nil] forCellWithReuseIdentifier:@"CELL"];
collectionCell= [menuCollectionView dequeueReusableCellWithReuseIdentifier:@"CELL"
forIndexPath:indexPath];
MenuItems *item=[itemsfinal objectAtIndex:indexPath.row];
NSMutableString *str = [NSMutableString stringWithFormat:@"%@", item.itemImage];
NSLog(@" url %@",str);
UIImage *image = [UIImage imageWithContentsOfFile:[self loadImage:str]];
if(image !=nil){
collectionCell.menuRecipeImage.image = image;
collectionCell.activityIndicator.hidden = YES;
[collectionCell.activityIndicator stopAnimating];
}else{
collectionCell.activityIndicator.hidden = NO;
[collectionCell.activityIndicator startAnimating];
collectionCell.menuRecipeImage.image = [UIImage imageNamed:@"menudefualt.png"];
}
return collectionCell;
}
最佳答案
在cellForItemAtIndexPath
中,您应该设置事件指示器。然后开始在后台加载单元格的图像。加载图像后,将其应用到主线程上的单元格。
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
__block UICollectionViewCell* cell = [cv dequeueReusableCellWithReuseIdentifier:@"cell"
forIndexPath: indexPath];
// Placeholder text --
UILabel* label = [[UILabel alloc] initWithFrame:cell.bounds];
label.text = @"Downloading...";
[cell.contentView addSubview:label];
// Load image in background --
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
NSURL* url = [NSURL URLWithString: [NSString stringWithFormat:@"http://example.com/img/img%02lu.png", (long unsigned)indexPath.row]];
// Load and decode image --
NSData * imageData = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:imageData];
// Apply image on the main thread --
dispatch_sync(dispatch_get_main_queue(), ^{
UIImageView* iv = [[UIImageView alloc] initWithImage:image];
[cell.contentView addSubview:iv];
});
});
return cell;
}
实际示例...
关于objective-c - 如何在 UICollectionview 自定义单元格中显示 UI Activityindicator 直到图像在服务器端下载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27374755/