TabelViewCell高度自適應(yīng)

今天早上在CocoaChina上看到一個(gè)tableViewCell高度自適應(yīng)的demo,用到了SDAutoLayout這個(gè)第三方庫,覺得挺方便的.所以想給大家分享一下,上代碼.
我只創(chuàng)建2個(gè)控件,一個(gè)UIImageView和一個(gè)UIlabel.

Model.h

#import <Foundation/Foundation.h>

@interface Model : NSObject
@property(nonatomic, copy)NSString *coverimg;//圖片請求的url
@property(nonatomic, copy)NSString *content;//用戶發(fā)表的內(nèi)容
@property(nonatomic, copy)NSString *coverimg_wh;//真實(shí)圖片的尺寸,如"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
{
    //初始化并添加這兩個(gè)控件
    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];
    
    //這里自動(dòng)布局需要用到參照方位的概念
    _imageView.sd_layout
    .leftSpaceToView(self.contentView, 10)//表示_imageView左邊離contentView的距離是10.可以理解為_imageView的x坐標(biāo)與self.contentView的x坐標(biāo)的差值
    .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坐標(biāo)一樣
    .rightEqualToView(_imageView)//_label與_imageView的右邊間距也一樣,也就是說_label與_imageView的Width相同
    .autoHeightRatio(0);//只要設(shè)置了_label的寬度后,加上這句話就可以通過_label的文字自適應(yīng)高度了
}

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

    CGFloat bottomMargin = 10;
    _label.text = model.content;
    
    if (![model.coverimg_wh isEqualToString:@""]) {
        NSArray *array = [model.coverimg_wh componentsSeparatedByString:@"*"];//通過"*"截取字符串,獲得寬和高
        //將寬和高轉(zhuǎn)換成NSInteger類型
        NSInteger width = [array[0] floatValue];
        NSInteger height = [array[1] floatValue];
        CGFloat scale = height / width;//得到高和快的比例
        _imageView.sd_layout.autoHeightRatio(scale);//_imageView的寬度已經(jīng)確定了,通過這個(gè)比例得到_imageView的高度
        [_imageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
        bottomMargin = 10;
    }
    else
    {
        _imageView.sd_layout.autoHeightRatio(0);
    }
    
    //第一個(gè)參數(shù)是cell最下面的那個(gè)view,第二個(gè)參數(shù)是最下面那個(gè)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

其實(shí)這個(gè)第三方用起來還是挺簡單的,我的注釋應(yīng)該還是比較詳細(xì)吧

XMHNetWorking

這個(gè)是我通過AFNetWorking封裝的網(wǎng)絡(luò)請求方法


#import "XMHNetWorkingMethod.h"
#import "AFNetworking.h"
@implementation XMHNetWorkingMethod
+(void)getDataString:(NSString *)string BodyString:(NSDictionary *)bodyDic WithDataBlock:(void (^)(id))dataBlock
{
    //字符串轉(zhuǎn)碼
    string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet characterSetWithCharactersInString:string]];
    //創(chuàng)建管理者對象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //設(shè)置允許請求的類別
    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為空就執(zhí)行Get請求
        [manager GET:string parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            //請求成功執(zhí)行的操作
            dataBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //請求失敗執(zhí)行的操作
        }];
    }
    else
    {
        //否則執(zhí)行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"http://網(wǎng)絡(luò)請求的地址
#import "UIImageView+WebCache.h"http://用于下載圖片并保存到沙盒
#import "MJRefresh.h"http://刷新加載第三方
#import "XMHNetWorkingMethod.h"http://自己寫的網(wǎng)絡(luò)請求
#import "TableViewCell.h"http://自定義的tableViewCell
#import "UITableView+SDAutoTableViewCellHeight.h"http://自適應(yīng)高度
@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:^{
       //當(dāng)下拉刷新的時(shí)候刪除數(shù)組,重新獲取最新數(shù)據(jù)再添加到數(shù)組
        flag = 0;
        [_listArray removeAllObjects];
        [self getData];
    }];
    _tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        //當(dāng)加載的時(shí)候?qū)lag這個(gè)參數(shù)加10,再解析數(shù)據(jù),得到新的一組數(shù)據(jù)再放進(jìn)數(shù)組里
        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
{
    //第一個(gè)參數(shù)是tableviewcell,第二個(gè)參數(shù)是得到屏幕的寬度,這樣可以在橫屏的時(shí)候照樣自適應(yīng)
    [self.tableView startAutoCellHeightWithCellClass:[TableViewCell class] contentViewWidth:[UIScreen mainScreen].bounds.size.width];
    
    return _listArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    /* model 為模型實(shí)例尸昧, keyPath 為 model 的屬性名义桂,通過 kvc 統(tǒng)一賦值接口 */
    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來看看官方的解釋
好了,今天就到這里,謝謝大家

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市箱蟆,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌婆廊,老刑警劉巖碌冶,帶你破解...
    沈念sama閱讀 223,126評論 6 520
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異购桑,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)氏淑,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,421評論 3 400
  • 文/潘曉璐 我一進(jìn)店門勃蜘,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人假残,你說我怎么就攤上這事缭贡。” “怎么了?”我有些...
    開封第一講書人閱讀 169,941評論 0 366
  • 文/不壞的土叔 我叫張陵阳惹,是天一觀的道長谍失。 經(jīng)常有香客問我,道長莹汤,這世上最難降的妖魔是什么快鱼? 我笑而不...
    開封第一講書人閱讀 60,294評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮体啰,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘嗽仪。我一直安慰自己荒勇,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,295評論 6 398
  • 文/花漫 我一把揭開白布闻坚。 她就那樣靜靜地躺著沽翔,像睡著了一般。 火紅的嫁衣襯著肌膚如雪窿凤。 梳的紋絲不亂的頭發(fā)上仅偎,一...
    開封第一講書人閱讀 52,874評論 1 314
  • 那天,我揣著相機(jī)與錄音雳殊,去河邊找鬼橘沥。 笑死,一個(gè)胖子當(dāng)著我的面吹牛夯秃,可吹牛的內(nèi)容都是我干的座咆。 我是一名探鬼主播,決...
    沈念sama閱讀 41,285評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼仓洼,長吁一口氣:“原來是場噩夢啊……” “哼介陶!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起色建,我...
    開封第一講書人閱讀 40,249評論 0 277
  • 序言:老撾萬榮一對情侶失蹤哺呜,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后箕戳,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體某残,經(jīng)...
    沈念sama閱讀 46,760評論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,840評論 3 343
  • 正文 我和宋清朗相戀三年陵吸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了驾锰。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,973評論 1 354
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡走越,死狀恐怖椭豫,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤赏酥,帶...
    沈念sama閱讀 36,631評論 5 351
  • 正文 年R本政府宣布喳整,位于F島的核電站,受9級(jí)特大地震影響裸扶,放射性物質(zhì)發(fā)生泄漏框都。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,315評論 3 336
  • 文/蒙蒙 一呵晨、第九天 我趴在偏房一處隱蔽的房頂上張望魏保。 院中可真熱鬧,春花似錦摸屠、人聲如沸谓罗。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,797評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽檩咱。三九已至,卻和暖如春胯舷,著一層夾襖步出監(jiān)牢的瞬間刻蚯,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,926評論 1 275
  • 我被黑心中介騙來泰國打工桑嘶, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留炊汹,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,431評論 3 379
  • 正文 我出身青樓逃顶,卻偏偏與公主長得像兵扬,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個(gè)殘疾皇子口蝠,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,982評論 2 361

推薦閱讀更多精彩內(nèi)容