在我們使用UITableView的時候經常會遇到這樣的需求,Cell的高度各種各樣,不是固定的。解決辦法可以參考下面程式碼:
- Model
在Model中,我們定義四個屬性;
.h
@property (nonatomic,copy) NSString *name;
@property (nonatomic,copy) NSString *author;
@property (nonatomic,copy) NSString *summary;
@property (nonatomic,copy) NSString *img;
.m
-(void)setValue:(id)value forUndefinedKey:(NSString *)key{
}
複製程式碼
- View .h
#import <UIKit/UIKit.h>
@class healthBookModel;
@interface BooksTableViewCell : UITableViewCell
@property (nonatomic,strong) healthBookModel *model;
@property (weak, nonatomic) IBOutlet UIImageView *img;
@property (weak, nonatomic) IBOutlet UILabel *summary;
@property (weak, nonatomic) IBOutlet UILabel *author;
@property (weak, nonatomic) IBOutlet UILabel *name;
@end
複製程式碼
.m
-(void)setModel:(healthBookModel *)model{
_model = model;
_summary.text = model.summary;
_author.text = model.author;
_name.text = model.name;
[_img sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://tnfs.tngou.net/image%@",model.img]]];
}
複製程式碼
XIB: 在XIB檔案中 我們是讓summary這個Lable高度不確定 所以 我們只限定它的寬 和 高 ;
- Controller
Model和View準備好了以後 接下來在Controller中這樣做:
.m檔案中內容
#import "ViewController.h"
#import "healthBookModel.h"
#import "BooksTableViewCell.h"
#import "YYModel.h"
#import "MJRefresh.h"
#define WIDTH self.view.bounds.size.width
#define HEIGHT self.view.bounds.size.height
static NSString *cellReuseID = @"cellReuseID";
@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>{
NSInteger currentPage;
}
@property (strong, nonatomic) UITableView *mainTableView;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (assign, nonatomic) CGFloat originCellMaxY;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.originCellMaxY = [self getCellLastControlMaxY];
//呼叫建立TableView的方法
[self createTableView];
//設定標題
UILabel *Title = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 80, 40)];
Title.textColor = [UIColor whiteColor];
Title.backgroundColor = [UIColor clearColor];
Title.textAlignment = NSTextAlignmentCenter;
Title.text = @"健康書籍";
Title.font = [UIFont fontWithName:@"Helvetica-Bold" size:26];
self.navigationItem.titleView = Title;
[_mainTableView.mj_header endRefreshing];
}
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:YES];
//試圖將要出現的時候 開始重新整理資料
[_mainTableView.mj_header beginRefreshing];
}
-(void)getData{
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSString *httpUrl =[NSString stringWithFormat:@"http://www.tngou.net/api/book/list?id=&rows=10&page=%ld",(unsigned long)currentPage] ;
NSURL *url = [NSURL URLWithString:httpUrl];
NSURLSession *session = [NSURLSession sharedSession];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (!error&&data) {
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:1 error:nil];
NSNull *value = [NSNull null];
if (dict[@"tngou"]!=value) {
dispatch_async(dispatch_get_main_queue(), ^{
for (NSDictionary *myDict in dict[@"list"]) {
healthBookModel *model = [[healthBookModel alloc]init];
[model yy_modelSetWithDictionary:myDict];
[_dataArray addObject:model];
[_mainTableView reloadData];
[_mainTableView.mj_header endRefreshing];
[_mainTableView.mj_footer endRefreshing];
}
});
}
}
else{
currentPage--;
}
}];
[task resume];
});
});
}
//加在資料模型 初始化頁面 初始化陣列 請求資料
-(void)loadDataModel{
currentPage = 1;
if (!_dataArray) {
_dataArray = [NSMutableArray array];
}
[self getData];
}
-(void)createTableView{
_mainTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT) style:UITableViewStylePlain];
//註冊Cell
[_mainTableView registerNib:[UINib nibWithNibName:@"BooksTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellReuseID];
[self.view addSubview:_mainTableView];
//設定TableView的代理 資料來源
_mainTableView.delegate = self;
_mainTableView.dataSource = self;
//下拉重新整理的時候 加在資料模型
_mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
[self loadDataModel];
}];
//上拉加在更多的時候 頁數加1 請求資料
_mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
currentPage++;
[self getData];
}];
}
//返回TableView中行數
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//重用Cell
BooksTableViewCell *cell = [_mainTableView dequeueReusableCellWithIdentifier:cellReuseID ];
if (!cell) {
cell = (BooksTableViewCell*)[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier: cellReuseID];
}
//為Cell繫結的Model賦值
cell.model = _dataArray[indexPath.row];
// 獲取不確定文字的高度
NSString *content = cell.model.summary;
CGFloat testHeight = [self sizeWithFont:[UIFont systemFontOfSize:14.0] maxW:cell.frame.size.width withContent:content] + 10;
// 重新設定cell的frame.
CGRect frame = cell.frame;
frame.size.height = testHeight + self.originCellMaxY;
cell.frame = frame;
return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// 直接返回該indexPath對應cell的frame.size.height. (在cellForRowAtIndexPath方法中會重新更改)
BooksTableViewCell *cell = (BooksTableViewCell *)[self tableView:tableView cellForRowAtIndexPath:indexPath];
return cell.frame.size.height;
}
// 計算指定文字的高度
-(CGFloat)sizeWithFont:(UIFont *)font maxW:(CGFloat) maxW withContent:(NSString *)testStr{
NSDictionary *textAttrs = @{NSFontAttributeName : font};
CGSize size = CGSizeMake(maxW, MAXFLOAT);
return [testStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:textAttrs context:nil].size.height;
}
// 獲取cell最底部控制元件的最大Y值
-(CGFloat)getCellLastControlMaxY {
// 獲取cell中最底部的控制元件
BooksTableViewCell *tempCell = (BooksTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:@"BooksTableViewCell" owner:nil options:nil] lastObject];
UILabel *lastLabel = tempCell.author;
return lastLabel.frame.origin.y + lastLabel.bounds.size.height;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
複製程式碼
效果:
#再介紹另一種用起來比較簡單的
在UITableViewDelegate中這樣使用:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
CGFloat height = [HJTTableViewCell CellHeightForTableView:tableView indexPath:indexPath cellContentViewWidth:0 bottomOffset:10];
return height;
}
在cell繪製中加上
self.cellBottomView = self.nameLab;
就可以了
複製程式碼
效果圖:
具體程式碼: