Implementing dynamic UITableViewCell height on UITableView

转载 2013年12月03日 20:19:08

- (CGFloat)requiredHeight
        CGSize labelSize = [LblTitle.text sizeWithFont: [LblContent font]
                                     constrainedToSize: CGSizeMake(300.0f, 300.0f) 
                                         lineBreakMode: UILineBreakModeTailTruncation];
        return 42.0f + labelSize.height;
        return 60.0f;

In owner file (UITableViewDelegate):

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
    OOCommentCell *cell = (OOCommentCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];
    return [cell requiredHeight];


Implementing dynamic UITableViewCell height on UITableView

If you’ve used Twitter iOS application, then most probably you will notice that content streams differ in sizes based on the length of each tweets. And if we are implementing such as this in simplest way of doing this, we could be using UITableView’s heightForRowAtIndexPath delegate method and get/set the size of each string on the array:

For demonstrating this behavior, we’ll be creating a simple View based project that needs an NSMutableArray and a UITableView:

@interface TableTestViewController : UIViewController<UITableViewDelegate, UITableViewDataSource> {
    NSMutableArray *_quotes;
    UITableView *_tableView;

And setting up our _tableView and adding some test data with varying length of characters:

- (void)viewDidLoad
    [super viewDidLoad];
    _quotes = [[NSMutableArray alloc] initWithObjects: 
               @"I do the very best I know how-the very best I can; and I mean to keep doing so until the end. If the end brings me out all right, what is said against me won't amount to anything. If the end brings me out wrong, ten angels swearing I was right would make no difference.", 
               @"Be systematically heroic in little unnecessary points, do every day or two something for no other reason than its difficulty, so that, when the hour of need draws nigh, it may find you not unnerved or untrained to stand the test.", 
               @"The trick of it, she told herself, is to be courageous and bold and make a difference. Not change the world exactly, just the bit around you. Go out there with your double-first, your passion and your new Smith Corona electric typewriter and work hard at ... something. Change lives through art maybe. Write beautifully. Cherish your friends, stay true to your principles, live passionately and fully well. Experience new things. Love and be loved if at all possible. Eat sensibly. Stuff like that.", 
               @"I know of no more encouraging fact than the unquestioned ability of a man to elevate his life by conscious endeavor.", nil];
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, 460) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;        

    [self.view addSubview: _tableView];

Our _tableView is set up to be the same UIWindow height less the size of Status bar (480 – 20). And setting the current view implements its delegate. Then, add our _tableView as a subview to our main view.

Let’s implement _tableView’s delegate and dataSource:

#pragma mark - UITableViewDataSource methods

- (NSInteger)tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section {
    return [_quotes count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString* reuseIdentifier = @"Cell";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (nil == cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier] autorelease];
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.textLabel.numberOfLines = 0;
    cell.textLabel.text = [_quotes objectAtIndex:indexPath.row];
    return cell;

Code above is pretty standard code for Table-view based application. The interesting code to notice is thenumberOfLines = 0, this tells us that cell will contain a multi-line string with unknown size. If we forgot to set this property to 0, the default value of 1 will be in effect causing our text to display and truncated in a single line.

#pragma mark - UITableViewDelegate methods

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGSize size = [[_quotes objectAtIndex:indexPath.row] 
                   sizeWithFont:[UIFont systemFontOfSize:14] 
                   constrainedToSize:CGSizeMake(300, CGFLOAT_MAX)];
    return size.height + 10;

In order to achieve our dynamic height nature of our cells, heightForRowAtIndexPath will do the trick. So for each cell iteration, it also gets the size of the string including its font size to the count. The constrainedToSizeparameter is the maximum acceptable size of the string. We set the height to be the constant max value ofCGFLOAT but you can set it manually to a higher number, say 5000 or 9000. After we get the size of the current string on the cell, we added 10 more to the height for readability purpose.

你真的懂得tableview cell的两个重用方法嘛

先说一下tableview  cell的两个重用方法(一下是iOS的描述) - (nullable __kindof UITableViewCell *)dequeueReusable...
  • u013404912
  • u013404912
  • 2016年03月22日 15:30
  • 660


方式一:自定义Cell,重写setFrame:方法,在调用父类方法[super setFrame:fame];之前减掉cell的高度:frame.size.height -= 10;减去的值即为分隔线...
  • vbirdbest
  • vbirdbest
  • 2016年09月13日 12:11
  • 4783


At first glance setting a height dynamically for table view cells seems a little daunting and the fi...
  • u010944926
  • u010944926
  • 2013年12月16日 16:18
  • 567


  • dipolar
  • dipolar
  • 2017年05月18日 18:54
  • 430


一.UITableView概述  1.UITableView继承自UIScrollView,可以表现为Plain和Grouped两种风格(具体区别的话大家可以自行试验,区别还是蛮大,不过因为iOS7扁...
  • humingtao2013
  • humingtao2013
  • 2014年03月09日 10:19
  • 10481


1·捉摸不定的contentOffset UISrollview在滑动的时候,我们要获取其不断变化的contentOffset值,即可通过其协议来获取也可以在其layoutSubviews里...
  • neveraway1993
  • neveraway1993
  • 2016年08月02日 11:54
  • 484

UITableViewCell 令人蛋疼的分割线!!!!

你一定会遇到这样的需求: 使用UITableView来进行数据的展示,要求有分隔线,并且使分割线顶格。。。。 你肯定这么干过 这样... tableView.separatorInset = U...
  • NB_Token
  • NB_Token
  • 2016年07月20日 17:16
  • 3607


关于row height的自动计算   至少需要满足3个条件 1 tableView.rowHeight = UITableViewAutomaticDimension 2 tableV...
  • dayuqi
  • dayuqi
  • 2016年12月28日 18:36
  • 597


插入一个cell。也可插入多个 *** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/L...
  • CornerAndCorner
  • CornerAndCorner
  • 2016年06月23日 19:00
  • 1398


解决UITableViewCell重绘出现重叠的现象案例: 固定的广播栏更换滚动多条信息重复加载出现复用! 当我们的UITableView为透明或者判断cell是否为空时,会发现每次刷新或者滑动T...
  • ws1352864983
  • ws1352864983
  • 2016年08月19日 10:32
  • 1161
您举报文章:Implementing dynamic UITableViewCell height on UITableView