【问题标题】:Calculate UITableViewCell height to fit string计算 UITableViewCell 高度以适合字符串
【发布时间】:2014-04-15 08:03:13
【问题描述】:

我有一个NSMutableArray,它可能包含数百个不同的字符串。每个字符串都是用户定义的,可以有任意长度,但不超过一个平均段落。

我需要找出每个字符串可以占用多少行。所以,我可以计算每个UITableviewCell 所需的高度。

【问题讨论】:

  • 你可以在UITableViewCell 中使用UITextView 吗?
  • 什么是NSMutable*????
  • 我没有理由不这样做,我更改了我也可以在 textview 上使用的字体大小、字体、文本颜色、背景颜色道具。
  • 抱歉,自动更正决定 NSMutableArray 不存在,但 NSMutable 存在
  • UITextView 旁边我看到了这个选项:stackoverflow.com/questions/19398674/…

标签: ios uitableview


【解决方案1】:

使用以下代码计算和设置单元格的高度:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Define `veryverySmallTitleFont`
    // Define `descLabel`

    NSString *ourText = @"Your string data from array";
    UIFont *font = [UIFont fontWithName:@"Verdana" size:veryverySmallTitleFont];
    font = [font fontWithSize:veryverySmallTitleFont];

    CGSize constraintSize = CGSizeMake(descLabel.frame.size.width, 1000);
    CGSize labelSize = [ourText sizeWithFont:font
                           constrainedToSize:constraintSize
                               lineBreakMode:UILineBreakModeWordWrap];

    return labelSize.height;
}

【讨论】:

  • sizeWithFont:constrainedToSize:lineBreakMode 现已弃用。
【解决方案2】:

我个人使用一种方便的方法,然后我会在tableView:heightForRowAtIndexPath: 中发送消息

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [self cellHeightForRowAtIndexPath:indexPath];
}

- (CGFloat)cellHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellString = <YOUR MODEL OBJECT>;

    NSDictionary *attributes = @{ NSFontAttributeName: [UIFont systemFontOfSize:16.0f] };
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc]
                                                   initWithString:cellString
                                                   attributes:attributes];

    CGFloat width = self.tableView.frame.size.width - 32.0f;
    CGRect frame = [attributedString boundingRectWithSize:CGSizeMake(width, MAXFLOAT)
                    options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    // Add some extra padding to the height
    CGFloat height = frame.size.height + 16.0f;

    return ceil(height);
}

当然,我在UITableViewCell 中将UILabelnumberOfLines 属性设置为0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-24
    • 1970-01-01
    相关资源
    最近更新 更多