1.主要針對(duì)的布局方式是約束布局 可以是xib 也可以是masonry
2.系統(tǒng)要求iOS8及以上版本
3.注意:如果出現(xiàn)高度計(jì)算不對(duì),可能是約束設(shè)置不對(duì),解決辦法重新設(shè)置約束
4.實(shí)現(xiàn)思路:第一步是設(shè)置預(yù)設(shè)高度 第二步自動(dòng)計(jì)算高度 第三步高度緩存
5.附源碼
主要代碼:
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 100;
次要代碼:
\#import "ListViewController.h"
\#import "ListTableViewCell.h"
static NSString * const ReuseIdentifier = @"cell";
@interface ListViewController ()
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@end
@implementation ListViewController
-(void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.title = @"標(biāo)題";
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"reloaData" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemDidClick:)];
[self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ListTableViewCell class]) bundle:nil] forCellReuseIdentifier:ReuseIdentifier];
}
#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ReuseIdentifier forIndexPath:indexPath];
cell.model = self.dataArray[indexPath.row];
return cell;
}
#pragma mark - Methods
- (void)rightBarButtonItemDidClick:(UIBarButtonItem *)item {
[self.tableView reloadData];
}
#pragma mark - Getters
-(NSMutableArray *)dataArray {
if (!_dataArray) {
_dataArray = [NSMutableArray array];
NSString *string = @"Siri 讓你能夠利用語(yǔ)音來(lái)完成發(fā)送信息、安排會(huì)議、查看最新比分等更多事務(wù)。只要說(shuō)出你想做的事,Siri 就能幫你辦到。Siri 可以聽(tīng)懂你說(shuō)的話、知曉你的心意,甚至還能有所回應(yīng)。iOS 7 中的 Siri 擁有新外觀、新聲音和新功能。它的界面經(jīng)過(guò)重新設(shè)計(jì),以淡入視圖浮現(xiàn)于任意屏幕畫(huà)面的最上層。Siri 回答問(wèn)題的速度更快,還能查詢更多信息源,如維基百科。它可以承擔(dān)更多任務(wù),如回電話、播放語(yǔ)音郵件、調(diào)節(jié)屏幕亮度,以及更多。";
//生成假數(shù)據(jù)
for (int i = 0; i < 100; i++) {
ListModel *model = [[ListModel alloc] init];
NSInteger index = (arc4random()%(string.length / 20)) * 20;
model.desc = [string substringToIndex:MAX(20, index)];
[_dataArray addObject:model];
}
}
return _dataArray;
}
@end
// 緩存用全局字典存
#pragma mark - UITableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath {
NSNumber *height = [self.heightAtIndexPath objectForKey:indexPath];
if(height){
return height.floatValue;
}
else {
return 100;
}
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
NSNumber *height = @(cell.frame.size.height);
[self.heightAtIndexPath setObject:height forKey:indexPath];
}