iOS 利用iOS8新特性(Self Sizing Cells)計算cell的實際高度

在iOS 8中沼撕,蘋果引入了UITableView的一項新功能--Self Sizing Cells渔隶,對于不少開發(fā)者來說這是新SDK中一項非常有用的新功能。在iOS 8之前腻格,如果想在表視圖中展示可變高度的動態(tài)內(nèi)容時平委,你需要手動計算行高,而Self Sizing Cells為展示動態(tài)內(nèi)容提供了一個解決方案夺谁。這個方法即對系統(tǒng)cell有效廉赔,也對xib創(chuàng)建的和自定義的cell有效。

1.以前我是這樣計算高度的

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellStr = self.contentAry[indexPath.row];

   CGSize cellSize=[cellStr boundingRectWithSize:CGSizeMake(self.view.frame.size.width-20, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;

    //cellSize的高度為文字的真實高度匾鸥,需要上下都留出空白蜡塌,這里+30的高度
    return cellSize.height+30;
}

如果是簡單的文字,那么很簡單的計算一下就OK了勿负,但是如果附帶圖片馏艾,文字等內(nèi)容呢?

現(xiàn)在研究了一下Self Sizing Cells奴愉,發(fā)現(xiàn)很好用琅摩。

2.系統(tǒng)方法計算高度

在這里我是配合Masonry進(jìn)行坐標(biāo)計算的。
在你創(chuàng)建tableview的地方添加锭硼,使用Self Sizing Cells時需要注意的事項:
1.為原型單元格定義Auto Layout約束
2.指定表視圖的estimatedRowHeight
3.將表視圖的rowHeight屬性設(shè)置為UITableViewAutomaticDimension

self.tableView.estimatedRowHeight = 100; //  隨便設(shè)個值
self.tableView.rowHeight = UITableViewAutomaticDimension;

下面貼上代碼:

ViewController.h
//
//  ViewController.m
//  Tableview自適應(yīng)高度
//
//  Created by XieHenry on 17/3/8.
//  Copyright ? 2017年 XieHenry. All rights reserved.
//

#import "ViewController.h"
#import "TableViewCell.h"

@interface ViewController () <UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *contentAry;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"cell自適應(yīng)高度";
    
    self.tableView = [[UITableView alloc]initWithFrame:[UIScreen mainScreen].bounds style:(UITableViewStylePlain)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    self.tableView.estimatedRowHeight = 100;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    [self.view addSubview:self.tableView];

    
    
    self.contentAry = @[@"設(shè)置固定高度100,其余的設(shè)置為自適應(yīng)高度--00",@"測試--01",@"測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試--02",@"測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試測試--03"];
    [self.tableView reloadData];
    
}

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

/*
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *cellStr = self.contentAry[indexPath.row];

   CGSize cellSize=[cellStr boundingRectWithSize:CGSizeMake(self.view.frame.size.width-20, 2000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13]} context:nil].size;

    //cellSize的高度為文字的真實高度房资,需要上下都留出空白,這里+30的高度
    return cellSize.height+30;
}
*/

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    //如果有必須的固定高度檀头,可以設(shè)置固定的轰异,沒有固定的,可以設(shè)置自適應(yīng)高度
    if (indexPath.row == 0) {
        return 100;
    } else {
        return UITableViewAutomaticDimension;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.contentAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ID = @"cell";
    //利用系統(tǒng)自帶cell類型
    TableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (cell == nil) {
        cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }

    cell.contentLabel.text = self.contentAry[indexPath.row];
    return cell;
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end

TableViewCell.h
#import <UIKit/UIKit.h>

@interface TableViewCell : UITableViewCell
@property (nonatomic,strong) UILabel *contentLabel;

@end
TableViewCell.m
#import "TableViewCell.h"
#import "Masonry.h"

@implementation TableViewCell
-(instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self createCell];
    }
    return self;
}
 
-(void)createCell{
    _contentLabel = [[UILabel alloc]init];
     _contentLabel.numberOfLines = 0;
    _contentLabel.font = [UIFont systemFontOfSize:13];
    [self.contentView addSubview:_contentLabel];

    [_contentLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.contentView).offset(10);
        make.right.mas_equalTo(self.contentView).offset(-10);
        make.top.mas_equalTo(self.contentView).offset(10);
        make.bottom.mas_equalTo(self.contentView).offset(-10);
    }];

    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = [UIColor grayColor];
    [self.contentView addSubview:lineView];
    
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.contentView);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(-0);
        make.height.mas_equalTo(0.5);
    }];
}
@end

本文Demo暑始。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末搭独,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子廊镜,更是在濱河造成了極大的恐慌牙肝,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異惊奇,居然都是意外死亡互躬,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進(jìn)店門颂郎,熙熙樓的掌柜王于貴愁眉苦臉地迎上來吼渡,“玉大人,你說我怎么就攤上這事乓序∷吕遥” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵替劈,是天一觀的道長寄雀。 經(jīng)常有香客問我,道長陨献,這世上最難降的妖魔是什么盒犹? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮眨业,結(jié)果婚禮上急膀,老公的妹妹穿的比我還像新娘。我一直安慰自己龄捡,他們只是感情好卓嫂,可當(dāng)我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著聘殖,像睡著了一般晨雳。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上奸腺,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天餐禁,我揣著相機(jī)與錄音,去河邊找鬼洋机。 笑死坠宴,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的绷旗。 我是一名探鬼主播喜鼓,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼衔肢!你這毒婦竟也來了庄岖?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤角骤,失蹤者是張志新(化名)和其女友劉穎隅忿,沒想到半個月后心剥,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡背桐,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年优烧,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片链峭。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡畦娄,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出弊仪,到底是詐尸還是另有隱情熙卡,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布励饵,位于F島的核電站驳癌,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏役听。R本人自食惡果不足惜颓鲜,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望典予。 院中可真熱鬧灾杰,春花似錦、人聲如沸熙参。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽孽椰。三九已至,卻和暖如春凛篙,著一層夾襖步出監(jiān)牢的瞬間黍匾,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工呛梆, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留锐涯,地道東北人。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓填物,卻偏偏與公主長得像纹腌,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子滞磺,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容