UITableView的Cell自適應高度

奮斗的郅博

###背景:
在計算cell的實際高度時我們一般是通過計算frame通過拿到最底部一個控件的最大Y值從而得到cell的高度算來算去比較麻煩

其實,iOS8已經(jīng)提供了直接通過Cell高度自適應的方法了,根本不用計算Cell高度,就可以搞定不等高Cell 這個方法即對系統(tǒng)cell有效 也對通多xib創(chuàng)建的cell有效:

具體實現(xiàn)場景

#import "TESTTableViewController.h"
#import "TESTTableViewCell.h"
@interface TESTTableViewController ()
@property (nonatomic,strong) NSArray *contentAry;
@end

@implementation TESTTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.estimatedRowHeight = 100;  //  隨便設個不那么離譜的值
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.contentAry = @[@"哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈",@"啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈",@"哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈哈哈哈"];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *ID = @"cell";
    
    //利用系統(tǒng)自帶cell類型
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];        
    }
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.text = self.contentAry[indexPath.row];
   return cell;
    
}
@end
實現(xiàn)效果圖

小結:

設置tableView的估算Cell高度和rowHeight值為自動計算模式(具體實現(xiàn)原理)

self.tableView.estimatedRowHeight = 100;  //  隨便設個不那么離譜的值
self.tableView.rowHeight = UITableViewAutomaticDimension;
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容