iOS 调整UITableViewCell中的imageView 的图片大小

77 篇文章 0 订阅
9 篇文章 0 订阅

当我们在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;
}

很开心。。。完美解决

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值