TabelViewCell高度自适应

今天早上在CocoaChina上看到一个tableViewCell高度自适应的demo,用到了SDAutoLayout这个第三方库,觉得挺方便的.所以想给大家分享一下,上代码.
我只创建2个控件,一个UIImageView和一个UIlabel.

Model.h

#import <Foundation/Foundation.h>

@interface Model : NSObject
@property(nonatomic, copy)NSString *coverimg;//图片请求的url
@property(nonatomic, copy)NSString *content;//用户发表的内容
@property(nonatomic, copy)NSString *coverimg_wh;//真实图片的尺寸,如"640*857"
@end

自定义的tableViewCell

//TableView.h
#import <UIKit/UIKit.h>
#import "Model.h"
@interface TableViewCell : UITableViewCell
@property(nonatomic, strong)Model *model;
@end

//TableView.m
#import "TableViewCell.h"
#import "UIView+SDAutoLayout.h"
#import "UITableView+SDAutoTableViewCellHeight.h"
#import "UIImageView+WebCache.h"
@implementation TableViewCell

{
    UIImageView *_imageView;//图片
    UILabel *_label;//文字
}

-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self createView];
    }
    return self;
}

-(void)createView
{
    //初始化并添加这两个控件
    UIImageView *view0 = [UIImageView new];
    view0.backgroundColor = [UIColor whiteColor];
    _imageView = view0;
    
    UILabel *view1 = [UILabel new];
    view1.textColor = [UIColor lightGrayColor];
    view1.font = [UIFont systemFontOfSize:16];
    _label = view1;
    [self.contentView addSubview:view0];
    [self.contentView addSubview:view1];
    
    //这里自动布局需要用到参照方位的概念
    _imageView.sd_layout
    .leftSpaceToView(self.contentView, 10)//表示_imageView左边离contentView的距离是10.可以理解为_imageView的x坐标与self.contentView的x坐标的差值
    .rightSpaceToView(self.contentView, 10)//同上,_imageView右边离contentView最右边的距离
    .topSpaceToView(self.contentView, 10);//_imageView的最上面离contentView的距离
    
    _label.sd_layout
    .topSpaceToView(_imageView, 10)//_label上方里_imageView的距离是10
    .leftEqualToView(_imageView)//_label与_imageView的左边间距一样,也就是x坐标一样
    .rightEqualToView(_imageView)//_label与_imageView的右边间距也一样,也就是说_label与_imageView的Width相同
    .autoHeightRatio(0);//只要设置了_label的宽度后,加上这句话就可以通过_label的文字自适应高度了
}

-(void)setModel:(Model *)model
{

    CGFloat bottomMargin = 10;
    _label.text = model.content;
    
    if (![model.coverimg_wh isEqualToString:@""]) {
        NSArray *array = [model.coverimg_wh componentsSeparatedByString:@"*"];//通过"*"截取字符串,获得宽和高
        //将宽和高转换成NSInteger类型
        NSInteger width = [array[0] floatValue];
        NSInteger height = [array[1] floatValue];
        CGFloat scale = height / width;//得到高和快的比例
        _imageView.sd_layout.autoHeightRatio(scale);//_imageView的宽度已经确定了,通过这个比例得到_imageView的高度
        [_imageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
        bottomMargin = 10;
    }
    else
    {
        _imageView.sd_layout.autoHeightRatio(0);
    }
    
    //第一个参数是cell最下面的那个view,第二个参数是最下面那个View离cell底部的距离
    [self setupAutoHeightWithBottomView:_label bottomMargin:bottomMargin];
}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

@end

其实这个第三方用起来还是挺简单的,我的注释应该还是比较详细吧

XMHNetWorking

这个是我通过AFNetWorking封装的网络请求方法


#import "XMHNetWorkingMethod.h"
#import "AFNetworking.h"
@implementation XMHNetWorkingMethod
+(void)getDataString:(NSString *)string BodyString:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock
{
    //字符串转码
    string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:string]];
    //创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //设置允许请求的类别
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html", @"application/javascript", @"text/js",@"application/x-javascript", nil];
    //开始请求
    if (!bodyDic) {
        //如果BodyString为空就执行Get请求
        [manager GET:string parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            //请求成功执行的操作
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //请求失败执行的操作
        }];
    }
    else
    {
        //否则执行POST请求
        [manager POST:string parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}
@end

ViewController

#import "ViewController.h"
#define POSTURLSTRING @"http://api2.pianke.me/timeline/list"//网络请求的地址
#import "UIImageView+WebCache.h"//用于下载图片并保存到沙盒
#import "MJRefresh.h"//刷新加载第三方
#import "XMHNetWorkingMethod.h"//自己写的网络请求
#import "TableViewCell.h"//自定义的tableViewCell
#import "UITableView+SDAutoTableViewCellHeight.h"//自适应高度
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)NSMutableArray *listArray;
@end
static NSInteger flag = 0;
@implementation ViewController

-(void)loadView
{
    [super loadView];
    self.listArray = [NSMutableArray array];
    [self getData];
    //初始化tableview
    _tableView = [[UITableView alloc]initWithFrame:self.view.frame];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    //MJRefresh刷新加载的方法
    [self.tableView.header beginRefreshing];
    _tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
       //当下拉刷新的时候删除数组,重新获取最新数据再添加到数组
        flag = 0;
        [_listArray removeAllObjects];
        [self getData];
    }];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //当加载的时候将flag这个参数加10,再解析数据,得到新的一组数据再放进数组里
        flag += 10;
        [self getData];
    }];
}

-(void)getData
{
    NSString *str = [NSString stringWithFormat:@"%ld",flag];
    
    [XMHNetWorkingMethod getDataString:POSTURLSTRING BodyString:[NSDictionary dictionaryWithObjectsAndKeys:str,@"start",@"10",@"limit",@"2",@"client", nil] WithDataBlock:^(id data) {
        //KVC赋值,_listArray里放的全是model类型对象
        
        NSDictionary *dataDic = [data objectForKey:@"data"];
        NSArray *array = [dataDic objectForKey:@"list"];
        for (NSDictionary *dic in array) {
            Model *model = [[Model alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [_listArray addObject:model];
        }
        [_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_tableView reloadData];
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //第一个参数是tableviewcell,第二个参数是得到屏幕的宽度,这样可以在横屏的时候照样自适应
    [self.tableView startAutoCellHeightWithCellClass:[TableViewCell class] contentViewWidth:[UIScreen mainScreen].bounds.size.width];
    
    return _listArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /* model 为模型实例, keyPath 为 model 的属性名,通过 kvc 统一赋值接口 */
    return [self.tableView cellHeightForIndexPath:indexPath model:self.listArray[indexPath.row] keyPath:@"model"];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ID = @"test";
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    cell.model = self.listArray[indexPath.row];
    return cell;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

成功之后截图

Simulator Screen Shot 2015年12月1日 下午2.39.32.png

大家可以去github上查看SDAutoLayout来看看官方的解释
好了,今天就到这里,谢谢大家

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

推荐阅读更多精彩内容