2014-01-20 43 views
2

我正在尝试制作一个与XCode 4.2的Twitter客户端。 (iOS version 5)。我想我的应用程序的主时间轴类似于Twitter的iOS应用的时间表:在iOS应用程序中动态调整表格单元格

Twitter's UI

我使用含标签和三个按钮的原型细胞UITableView。下面是我使用的设置高度的代码:

  - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath 
      { 
       static NSString* cellIdentifier = @"TweetContainerCell"; 
       UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; 
       @try { 
        UILabel* tweetLabel; 
        if(cell != nil) { 
         tweetLabel = (UILabel*)[cell.contentView viewWithTag:1]; 
         NSString* tweetText = tweetLabel.text; 
         CGSize expectedLabelSize = [tweetText sizeWithFont:[UIFont fontWithName:tweetLabel.font.fontName size:20] constrainedToSize:CGSizeMake(CGFLOAT_MIN, CGFLOAT_MAX) lineBreakMode:UILineBreakModeWordWrap]; 
         //[tweetLabel setFrame:CGRectMake(tweetLabel.frame.origin.x, tweetLabel.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)]; 
         //[cell.textLabel setFrame:tweetLabel.bounds]; 
         //[tweetLabel sizeToFit]; 
         //[cell setFrame:CGRectMake(cell.frame.origin.x, cell.frame.origin.y, cell.frame.size.width, expectedLabelSize.height)]; 
         //[cell sizeToFit]; 
         NSLog(@"Font size: %f", expectedLabelSize.height); 
         return (expectedLabelSize.height * 2); 
        } 
       } 
       /* Imgur URL: http://i.imgur.com/lHnsAsP.png */ 
       /* http://i.imgur.com/hA9EKfI.png */ 
       @catch (NSException* exception) { 
        NSLog(@"Exception: %@", exception); 
       } 
       return 0; 
      } 

但是,这是我的应用程序最终看起来像:

My application

的问题是:

1 )每个单元格与整个表格中最高的单元格的高度相似,而不是具有不同的高度。

2)因此,单元格的上边框和文本之间的间距对于每个单元格都不同(因为iOS垂直居中文本)。

我正在学习iOS发展和无法做这么简单的事情,即使经过大量的研究和花费大量的时间,似乎真的令人沮丧。任何帮助是极大的赞赏。

(如果我所提供的信息是不够的,这是一个包含整个项目的ZIP文件:https://db.tt/m5suxWCj

回答

2

您的问题是你的标签尚未建立,因为tableView:heightForRowAtIndexPath:最初tableView:cellForRowAtIndexPath:之前调用,这是您的单元格创建的位置。在tableView:heightForRowAtIndexPath:你应该尽可能有效地确定单元格的高度,而不涉及UIViews。

为了达到这个目的,您应该在您的表格视图数据源中的其他地方存储NSString,并基于此计算expectedLabelSize

另请注意,在IOS 7中不推荐使用sizeWithFont:,因此对于IOS 7及更高版本,您应该使用sizeWithAttributes:代替。