我UIImageView
在我的UITableViewCell
. 我的图像视图是 100 点乘 100 点的正方形,但UIImage
我检索到的 s 并不总是具有相等的宽度和高度。
我的问题是:在加载单元格时,UIImageView
s 都是 100 x 100,这很好,但是内部UIImage
s 被拉伸到那个大小(左图)。当我按下单元格并突出显示时,图像会突然调整到正确的比例(右图)。此外,当我进一步向下滚动到 时UITableView
,所有图像也是 100x100 并被拉伸,但是当我向上滚动再次查看单元格时,它们已经突然调整大小了。不过,我不知道他们遵循的缩放比例。
我究竟做错了什么?我已经将UIImageView
s'设置contentMode
为,UIViewContentModeCenter
但如您所见,它不起作用。请帮忙?我的完整代码如下。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"searchResultCell"];
if (!cell) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"searchResultCell"];
}
// Get the Ad object that will be displayed in this cell.
Ad *ad = (Ad *)[self.searchResults objectAtIndex:indexPath.row];
// Set up the detail text on the right.
cell.textLabel.attributedText = ad.attributedTextDisplay;
cell.textLabel.numberOfLines = 0;
cell.textLabel.lineBreakMode = NSLineBreakByWordWrapping;
// Set up the image on the left.
NSString *thumbnailURL = ad.thumbnailURL;
NSData *data = [FTWCache objectForKey:[MD5 hash:thumbnailURL]];
// If the image has been previously downloaded and is stored in FTWCache.
if (data) {
// Then use that data instead.
cell.imageView.image = [UIImage imageWithData:data];
} else {
// Assign default image before beginning background image retrieval task.
cell.imageView.image = [UIImage imageNamed:@"image_stub_ad"];
// Trigger background task that retrieves the actual thumbnail from the URL.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:thumbnailURL]];
// Proceed only with updating the table view cell if the returned NSData is not nil.
if (imageData) {
dispatch_sync(dispatch_get_main_queue(), ^{
// UPDATED: Added call to setNeedsDisplay.
UITableViewCell *theSameCell = [tableView cellForRowAtIndexPath:indexPath];
theSameCell.imageView.image = [UIImage imageWithData:imageData];
[theSameCell setNeedsDisplay];
});
}
});
}
// UPDATED: Set the contentMode to UIViewContentModeScaleAspectFit instead of UIViewContentModeCenter.
cell.imageView.contentMode = UIViewContentModeScaleAspectFit;
return cell;
}