修改tableView中原生cell的imageView图片大小

前言

在cell中有一个imageView属性,可以设置每一个cell左边显示的图片。而默认的图片大小是根据cell的高度而决定的,我们并不能直接通过改变imageView.frame属性来达到改变图片大小的目的,因为这是一个readonly属性。


  • 错误提示
  • 正常设置图片
    • 高度跟行高一样
cell.imageView.image = [UIImage imageNamed:@"Dog4.jpg"];

  • 通过以下的代码来设置cell的imageView
    • 来实现改变image的大小
UIImage *image = [UIImage imageNamed:@"Dog4.jpg"];
CGSize imageSize = CGSizeMake(80, 80);
UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height);
[image drawInRect:imageRect];
cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsGetImageFromCurrentImageContext();

最后

注意先签<UITableViewDataSource>协议,然后设置代理,最后实现协议中下面这个方法

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
  • 完整代码
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reusableIdentifier = @"cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableIdentifier];
    //  如果cell为nil,代表没有可重用的cell,需要创建
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:reusableIdentifier] autorelease];
    }
     //  subtitle样式,上方的label
    cell.textLabel.text = [NSString stringWithFormat:@"init : %ld", indexPath.row];
    //  subtitle样式,下方的label
    cell.detailTextLabel.text = [NSString stringWithFormat:@"Reusable : %ld", indexPath.row];
    //  设置image的大小
    UIImage *image = [UIImage imageNamed:@"Dog4.jpg"];
    CGSize imageSize = CGSizeMake(80, 80);
    UIGraphicsBeginImageContextWithOptions(imageSize, NO, 0.0);
    CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height);
    [image drawInRect:imageRect];
    cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsGetImageFromCurrentImageContext();
    return cell;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥iOS动画全貌。在这里你可以看...
    F麦子阅读 10,570评论 5 13
  • 在第13章“高效绘图”中,我们研究了和Core Graphics绘图相关的性能问题,以及如何修复。和绘图性能相关紧...
    雪_晟阅读 3,880评论 0 0
  • 在iOS中随处都可以看到绚丽的动画效果,实现这些动画的过程并不复杂,今天将带大家一窥ios动画全貌。在这里你可以看...
    每天刷两次牙阅读 12,733评论 6 30
  • { 11、核心动画 需要签协议,但是系统帮签好 一、CABasicAnimation 1、创建基础动画对象 CAB...
    CYC666阅读 5,550评论 2 4
  • 本文转载自:http://www.cocoachina.com/ios/20150106/10840.html 为...
    idiot_lin阅读 4,021评论 0 1

友情链接更多精彩内容