我正在我的 iPhone 应用程序中从网络加载图像。我将此图像用于表格单元格的 ImageView 。应用程序启动后几秒钟,所有图像都已完全加载。但表格的滚动不流畅。有延迟。滚动发生在手势后几秒钟。还有抽搐。我正在使用这段代码
UIImage *imagefromWeb = [UIImage imageWithData:[NSData dataWithContentsOfURL:[IconArray objectAtIndex:indexPath.row]]];
CGSize newSize= CGSizeMake(45.0,45.0);
UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
[imagefromWeb drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
cell.imageView.image=newImage;
最佳答案
您正在同步加载图片,这就是问题所在,请尝试使用以下代码异步下载图片:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(queue, ^{
NSURL *imageURL=[NSURL URLWithString:urlString];
NSData *imageData=[NSData dataWithContentsOfURL:imageURL];
dispatch_sync(dispatch_get_main_queue(), ^{
CustomCell *cell = (CustomCell *)[tableView cellForRowAtIndexPath:indexPath];
cell.imageView.image=[UIImage imageWithData:imageData];
[cell setNeedsLayout];
});
});
关于iphone - 从网络加载图像使应用程序挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14097363/