当我们在iOS中实现带图片带列表显示时UITableViewCell中自带了一个存放图片的控件UIImageView,当我们获取的图片大小一致时,图片能够很整齐大显示,可是有些时候我们获取的列表图片的大小并不完全一致,为了保证界面的美观我们必须调整图片大小或位置,可是当我们在定义好的UITableViewCell对象中设置cell.imageView.bounds、cell.imageView.frame时发现无论设置什么值都无法改变图片的大小和位置。
解决办法一:
给UITableViewCell的成员设置框架属性后不起作用,解决办法是在UITableViewCell的子类中重写layoutSubviews,在其中改变一些属性的值。
重定义一个uitableviewcell,它自动生成的代码不需要动,只要在.m文件中再加上下面的代码即可:
- (void)layoutSubviews {
[superlayoutSubviews];
self.imageView.bounds =CGRectMake(0,0,44,44);
self.imageView.frame =CGRectMake(0,0,44,44);
self.imageView.contentMode =UIViewContentModeScaleAspectFit;
CGRect tmpFrame = self.textLabel.frame;
tmpFrame.origin.x = 46;
self.textLabel.frame = tmpFrame;
tmpFrame = self.detailTextLabel.frame;
tmpFrame.origin.x = 46;
self.detailTextLabel.frame = tmpFrame;
}
解决办法二:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
[...]
//1、首先对image付值
cell.imageView.image=[UIImage imageNamed:@"default_image"];
//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;
}
很开心。。。完美解决