今天早上在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來看看官方的解釋
好了,今天就到這里,謝謝大家