use*_*762 10 objective-c uitableview uiimageview ios
我使用异步块(Grand central dispatch)来加载我的单元格图像.但是,如果你快速滚动它们仍然会出现但速度非常快,直到它加载了正确的一个.我确定这是一个常见的问题,但我似乎无法找到它.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
// Load the image with an GCD block executed in another thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[[appDelegate offersFeeds] objectAtIndex:indexPath.row] imageurl]]];
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *offersImage = [UIImage imageWithData:data];
cell.imageView.image = offersImage;
});
});
cell.textLabel.text = [[[appDelegate offersFeeds] objectAtIndex:indexPath.row] title];
cell.detailTextLabel.text = [[[appDelegate offersFeeds] objectAtIndex:indexPath.row] subtitle];
return cell;
}
Run Code Online (Sandbox Code Playgroud)
Rob*_*Rob 18
至少,您可能希望在以下情况之前从单元格中删除图像(如果它是重复使用的单元格)dispatch_async:
cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
Run Code Online (Sandbox Code Playgroud)
要么
cell.imageView.image = nil;
Run Code Online (Sandbox Code Playgroud)
您还希望在更新之前确保相关单元格仍在屏幕上(通过使用该UITableView方法,如果该行的单元格不再可见,则cellForRowAtIndexPath:返回该方法,nil不要与该UITableViewDataDelegate方法混淆tableView:cellForRowAtIndexPath:),例如:
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
cell.imageView.image = [UIImage imageNamed:@"placeholder.png"];
// Load the image with an GCD block executed in another thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[[appDelegate offersFeeds] objectAtIndex:indexPath.row] imageurl]]];
if (data) {
UIImage *offersImage = [UIImage imageWithData:data];
if (offersImage) {
dispatch_async(dispatch_get_main_queue(), ^{
UITableViewCell *updateCell = [tableView cellForRowAtIndexPath:indexPath];
if (updateCell) {
updateCell.imageView.image = offersImage;
}
});
}
}
});
cell.textLabel.text = [[[appDelegate offersFeeds] objectAtIndex:indexPath.row] title];
cell.detailTextLabel.text = [[[appDelegate offersFeeds] objectAtIndex:indexPath.row] subtitle];
return cell;
Run Code Online (Sandbox Code Playgroud)
坦率地说,您还应该使用缓存来避免不必要地重新检索图像(例如,您向下滚动一点并向上滚动,您不希望为这些先前单元格的图像发出网络请求).更好的是,您应该使用其中一个UIImageView类别(例如SDWebImage或AFNetworking中包含的类别).这样可以实现异步图像加载,但也可以优雅地处理缓存(不要重新检索几秒前刚刚检索到的图像),取消尚未发生的图像(例如,如果用户快速滚动到第100行,您可能不会我想在向用户显示第100行的图像之前等待前99检索.
| 归档时间: |
|
| 查看次数: |
11973 次 |
| 最近记录: |