我创建了一个 UITableView,它根据 URL 请求填充每个单元格。我使用“dispatch_queue”来防止 UItableView 冻结。由于某种原因,当我滚动 UITableView 时,图像会闪烁并消失,并填充错误的单元格一秒钟,直到自行修复。这是我的代码。我正在使用 Restkit 拉取 feed
customCell.customCellTextLabel.text = [NSString stringWithFormat:@"%@",feedO.title];
NSString *string = [NSString stringWithFormat:@"%@",feedO.body];
NSURL *urlString;
NSDataDetector *linkDetector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSArray *matches = [linkDetector matchesInString:string options:0 range:NSMakeRange(0, [string length])];
for (NSTextCheckingResult *match in matches) {
if ([match resultType] == NSTextCheckingTypeLink) {
urlString = [match URL];
NSLog(@"found Body URL: %@ and title %@", urlString,feedO.title);
}
}
dispatch_queue_t imageQueue = dispatch_queue_create("imageDownloader",nil);
dispatch_async(imageQueue, ^{
NSData *data = [[NSData alloc] initWithContentsOfURL:urlString];
dispatch_async(dispatch_get_main_queue(), ^{
customCell.customCellImageView.image = [UIImage imageWithData: data];
});
});
return customCell;
您应该考虑使用此库 SDWebImage,可在此处获取https://github.com/rs/SDWebImage https://github.com/rs/SDWebImage对于此类问题。它可以非常轻松地处理远程图像的异步下载和缓存。
最简单的安装是使用 CocoaPods 完成
可可豆荚 (http://cocoapods.org http://cocoapods.org) 是 Objective-C 的依赖管理器,它可以自动化并简化在项目中使用第 3 方库的过程。
有关更多详细信息,请参阅入门部分。
在你的 Podfile 中使用
platform :ios, '6.1'
pod 'SDWebImage', '~>3.6'
安装 SDWebImage 的依赖项后,只需在视图控制器中使用以下几行:
#import <SDWebImage/UIImageView+WebCache.h>
...
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:MyIdentifier] autorelease];
}
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
cell.textLabel.text = @"My Text";
return cell;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)