TabelViewCell高度自適應

weixin_33976072發表於2015-12-01

今天早上在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

成功之後截圖

1220329-62a58ae236963d0c.png
Simulator Screen Shot 2015年12月1日 下午2.39.32.png

大家可以去github上檢視SDAutoLayout來看看官方的解釋
好了,今天就到這裡,謝謝大家

相關文章