怎样让自定义Cell的图片和文本自适应高度

前言

首先我们需要明白为什么要让Cell里的图片或者文本自适应高度,因为很多时候Cell中的数据是通过网络请求得来的,我们在自定义Cell的时候并不能把Cel的高度给一个死值,否则会出现图片被压缩或者文字显示不全的情况。这个时候我们就要动态设置Cell的高度。


Let's do it!

  • 首先创建一个Model类
    • 包括一个图片名称属性
    • 还有文字内容属性
#import <Foundation/Foundation.h>

@interface Model : NSObject
@property (nonatomic, copy) NSString *imageName;
@property (nonatomic, copy) NSString *info;
@end
  • 自定义Cell
    • 创建一个继承于UITableViewCell的MyTableViewCell
    • 把模型作为属性
    • 在MyTableViewCell的延展里写一个UIImageView和UILabel属性
MyTableViewCell.h

#import <UIKit/UIKit.h>
@class Model;
@interface MyTableViewCell : UITableViewCell
@property (nonatomic, retain) Model *cellModel;
@end
MyTableViewCell.m

#import "MyTableViewCell.h"
#import "Model.h"
@interface MyTableViewCell ()

@property (nonatomic, retain) UIImageView *myImageView;
@property (nonatomic, retain) UILabel *myLabel;
@end
@implementation MyTableViewCell
- (void)dealloc {
    [_cellModel release];
    [_myImageView release];
    [_myLabel release];
    [super dealloc];
}
- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    
    self.myImageView = [[UIImageView alloc] initWithFrame:CGRectZero];
    [self.contentView addSubview:_myImageView];
    [_myImageView release];
    
    self.myLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    _myLabel.numberOfLines = 0;
    [self.contentView addSubview:_myLabel];
    [_myLabel release];
    
    return self;
}

# pragma mark - override setter
- (void)setCellModel:(Model *)cellModel {
    if (_cellModel != cellModel) {
        [_cellModel release];
        _cellModel = [cellModel retain];
        _myImageView.image = [UIImage imageNamed:cellModel.imageName];
        _myLabel.text = cellModel.info;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    //  首先拿到图片的原尺寸
    CGSize size = _myImageView.image.size;
    //  用固定的宽度除以图片原宽,得到一个比例
    CGFloat scale = self.contentView.frame.size.width / size.width;
    //  根据比例求得固定的高度
    CGFloat realHeight = size.height * scale;
    //  最后设置imageView的frame
    _myImageView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, realHeight);
    //  label的y坐标根据imageView的大小来决定,所以一定写在imageView高度计算之后
    _myLabel.frame = CGRectMake(0, _myImageView.frame.origin.y + _myImageView.frame.size.height, _myImageView.frame.size.width, 40);
    //  sizeToFit根据宽度算高度,所以一定要先有一个宽度(注意label显示行数需要设置为0)
    [_myLabel sizeToFit];
}
@end

  • 在根视图控制器里创建一个tableView
#import "RootViewController.h"
#import "Model.h"
#import "MyTableViewCell.h"

static NSString *const reusableIndentifier = @"cell";

@interface RootViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, retain) NSArray *array;

@end

@implementation RootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    Model *model = [[Model alloc] init];
    model.imageName = @"Dog4.jpg";
    model.info = @"Swift is a powerful and intuitive programming language for macOS, iOS, watchOS and tvOS. Writing Swift code is interactive and fun, the syntax is concise yet expressive, and Swift includes modern features developers love. Swift code is safe by design, yet also produces software that runs lightning-fast. Swift 3 is a thorough refinement of the language and the API conventions for the frameworks you use every day. These improvements make the code you write even more natural, while ensuring your code is much more consistent moving forward. For example, select Foundation types such as the new Date type are easier to use and are much faster than previous releases, and the Calendar type uses enums to feel more at home within Swift. SwiftSwiftSwiftSwiftSwiftSwiftSwift";
    
    self.array = @[model];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    tableView.backgroundColor = [UIColor cyanColor];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    [tableView release];
  
}
# pragma mark - 代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reusableIndentifier];
    if (nil == cell) {
        cell = [[MyTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reusableIndentifier];
    }
    cell.cellModel = _array[indexPath.row];
    return cell;
}

# pragma mark - 设置高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    Model *model = _array[indexPath.row];
    UIImage *image = [UIImage imageNamed:model.imageName];
    CGSize size = image.size;
    CGFloat scale = tableView.bounds.size.width / size.width;
    CGFloat realHeight = size.height * scale;
    
    //  label自适应高度
    //  首先定义一个字符变量接收模型里的info属性值
    NSString *info = model.info;
    //  宽度要和label宽度一样
    CGSize infoSize = CGSizeMake(tableView.frame.size.width, 1000);
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f]};
    //  计算文字高度
    //  参数1:自适应尺寸,提供一个宽度,去适应高度
    //  参数2:自适应设置(以行为矩形区域自适应,以字体字形自适应)
    //  参数3:文字属性,通常这里面需要知道的是字体大小
    //  参数4:绘制文本上下文,做底层排版时使用,填nil即可
    CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
    //  图片高度 + 文字高度
    //  上面方法在计算文字高度的时候可能得到的是带小数的值,如果用来做视图尺寸的适应的话,需要使用更大一点的整数值
    //  取整的方法使用ceil函数
    return realHeight + ceil(infoRect.size.height);
   
}
@end


文本自适应高度:根据文本内容设定Label高度

  • 关键代码
   //  label自适应高度
    //  首先定义一个字符变量接收模型里的info属性值
    NSString *info = model.info;
    //  宽度要和label宽度一样
    CGSize infoSize = CGSizeMake(tableView.frame.size.width, 1000);
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:17.f]};
    //  计算文字高度
    //  参数1:自适应尺寸,提供一个宽度,去适应高度
    //  参数2:自适应设置(以行为矩形区域自适应,以字体字形自适应)
    //  参数3:文字属性,通常这里面需要知道的是字体大小
    //  参数4:绘制文本上下文,做底层排版时使用,填nil即可
    CGRect infoRect = [info boundingRectWithSize:infoSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];

  • 效果图
    • 根据文字的多少动态改变cell的高度

图片自适应高度:根据图片宽度进行的等比例缩放

  • 关键代码
  • 注意:
    • 图片自适应高度的代码要在layoutSubview方法还有tableView:heightForRowAtIndexPath:方法中各写一遍
Model *model = _array[indexPath.row];
UIImage *image = [UIImage imageNamed:model.imageName];
CGSize size = image.size;
CGFloat scale = tableView.bounds.size.width / size.width;
CGFloat realHeight = size.height * scale;
  • 效果图
    • 更改定宽后的效果
    • 图片高度也按照比例缩小了

最后

TableView作为iOS开发中最重要的核心控件,几乎在市面上所有的APP中都能看到它的身影,所以学会熟练使用它非常有必要。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容

  • 1.xib方式创建 每个cell的显示的内容都是固定的,也就是cell的高度都是相同的 加载数据 有plist文件...
    WeiHing阅读 6,876评论 0 6
  • 我们在上一篇《通过代码自定义不等高cell》中学习了tableView的相关知识,本文将在上文的基础上,利用sto...
    啊世ka阅读 1,510评论 2 7
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,109评论 4 62
  • 「日晕天将雨,月晕午时风。」 最近的日子过得很慢,早上早早地起床去学车,赶着太阳行将露出回去。 我学车的训练场离家...
    向绿_阅读 375评论 3 3
  • 今天周六,让宝贝多睡一会觉,起床吃完饭就开始写作业,虽然有点感冒,但是还是认真的写作业,下午起床后本来说好去...
    李烽熠妈阅读 198评论 0 0