繁体   English   中英

带标签的 UITableViewCell 动态高度

[英]UITableViewCell dynamic height with label

我创建了一个带有 NIB 文件的 UITableViewCell。 其中有 1 个标签将包含一条推文。 所以它需要是一个动态高度。 还有一个 timeAgo 标签必须放在推文标签下面。

我正在尝试使用框架大小的东西,但我无法得到完美的解决方案。我在 UITableViewCell 文件中的 drawrect 方法中执行此操作。

self.tweet.lineBreakMode = UILineBreakModeWordWrap;
self.tweet.numberOfLines = 0;
self.tweet.font = [UIFont fontWithName:@"Arial" size:13.0f];
[self.tweet sizeToFit];  

CGFloat tweetHeight = self.tweet.frame.size.height;

self.timeAgo.lineBreakMode = UILineBreakModeWordWrap;
self.timeAgo.numberOfLines = 0;
self.timeAgo.font = [UIFont fontWithName:@"Arial" size:11.0f];
[self.timeAgo sizeToFit];

CGFloat timeAgoHeight = self.timeAgo.frame.size.height;

self.timeAgo.frame = CGRectMake(88, tweetHeight, 100, timeAgoHeight + 10.0f);

我还尝试了在教程中找到的 stringhelper。

这:

- (CGFloat)RAD_textHeightForSystemFontOfSize:(CGFloat)size {

我的 HeightForRow 方法也已经不同,因为我使用了不同的单元格样式。 目前我为每个单元格样式返回一个硬值,但这也需要更改为单元格高度。

请参阅本教程,http://www.cimgf.com/2009/09/23/uitableviewcell-dynamic-height/

诀窍是让标签随着单元格的大小而增长,而不是您只需设置单元格的大小,单元格就会随之增长。

设置 timeAgo 标签以将其与单元格底部对齐。

通过IB设置tweet的numberOfLines为0,重新移动所有绘制代码​​,只实现以下内容:

- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    id item  = [self.item objectAtIndex:indexpath.row];

    CGFloat height = 85.0f;

    if ([item isKindOfClass:[Tweet class]]) {
        Tweet *tweet = (Tweet *)item;
        CGSize titleSize = [tweet.tweet sizeWithFont:[UIFont fontWithName:@"Arial" size:13.0f] constrainedToSize:CGSizeMake(260.0f, MAXFLOAT)];

        // adde the 24 pixels to get the height plus the time ago label.
        height =  titleSize.height + 24.0f;

    } else if( [item isKinfOfClass:[SC_Release class]]) {
        height = 65.0f;
    }

   return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *string = [tweetsArray indexPath.row];
    CGSize labelSize = [string sizeWithFont:[UIFont fontWithName:@"Verdana" size:17.0] 
                                                     constrainedToSize:CGSizeMake(280.0f, MAXFLOAT) 
                                                         lineBreakMode:UILineBreakModeWordWrap];
    return labelSize.height + 20;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM