在我的項目中,很多地方都希望將UITableViewCell 中的imageView 能根據自己圖片的大小來進行展示,而就為了解決這個問題又覺得重寫UITableViewCell 很不值得。
如下:
:
其實我就只有 圖片變形的問題。所以我第一時間想到的是調整imageView 內容布局模式以及外框大小
cell.imageView.contentMode=UIViewContentModeCenter;
cell.imageView.frame=....
另外如:
cell.imageView.autoresizingMask = ( UIViewAutoresizingNone );
cell.imageView.autoresizesSubviews = NO;
cell.imageView.contentMode = UIViewContentModeCenter;
cell.imageView.bounds = CGRectMake(0, 0, 50, 50);
cell.imageView.frame = CGRectMake(0, 0, 50, 50);
cell.imageView.image = [UIImage imageWithData: imageData];
但是這些方法 在UITableViewCell里面都不起作用。。。。
在網上找了老半天也沒有找到,后來還是在stackoverflow 里面找到了一種自己比較喜歡的解決方案,如下:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[...]
//1、首先對image付值
cell.imageView.image=[UIImage imageNamed:@"灰時間"];
//2、調整大小
CGSize itemSize = CGSizeMake(40, 40);
UIGraphicsBeginImageContextWithOptions(itemSize, NO, UIScreen.mainScreen.scale);
CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
[cell.imageView.image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[...]
return cell;
}
結果如下:

很開心。。。完美解決
