怎样让自定义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中都能看到它的身影,所以学会熟练使用它非常有必要。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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