调整UITableViewCell内的UILabel大小以适应内容

时间:2014-06-30 15:41:02

标签: ios objective-c uitableview uilabel

我已成功调整了UITableViewCell的大小以适应它的内容,但我的UILabel没有正确调整大小。这就是我调整单元格大小的方法:

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    NSString *str = @"My really long text";
    CGSize constrainedSize = CGSizeMake(250, 9999);

    NSDictionary *attributesDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                          [UIFont fontWithName:@"HelveticaNeue-Light" size:16.0], NSFontAttributeName,
                                          nil];

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:str attributes:attributesDictionary];

    CGRect requiredHeight = [string boundingRectWithSize:constrainedSize options:NSStringDrawingUsesLineFragmentOrigin context:nil];

    if (requiredHeight.size.width > 250) {
        requiredHeight = CGRectMake(0,0, 250, requiredHeight.size.height);
    }

    if (requiredHeight.size.height + 10 >= 60)
        return requiredHeight.size.height + 10;
    else
        return 60;
}

我在Storyboard

中的原型单元格中创建了我的UILabel
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Post-Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    UILabel *text = (UILabel *)[cell viewWithTag:2];
    text.text = @"My Label's Text";
    [text sizeToFit];

    return cell;
}

1 个答案:

答案 0 :(得分:2)

我将它用于动态标签。首先我知道我的标签约束了左边60px和右边67。所以我知道我的标签在包装之前会有屏幕宽度减去填充以适应其内容。无论有多少行,这个方法都会给我title的高度。我将最低高度设置为44,这样即使用户有超级小文本,我仍然有一个不错的大小单元格。我的单元格中的标签从顶部开始是11像素,内容视图底部是11,所以我在填充高度上添加了22个。

+ (CGFloat)cellHeightForTitle:(NSString*)title
{
    UIFont *font = [UIFont preferredFontForTextStyle:UIFontTextStyleBody];
    NSString *text = title ?: @"test";
    CGFloat hotizontalPadding = 127;
    CGFloat desiredWidth = [UIScreen mainScreen].bounds.size.width - hotizontalPadding;
    NSAttributedString *attributedText = [[NSAttributedString alloc] initWithString:text attributes:@{NSFontAttributeName: font}];

    UILabel *label = [[UILabel alloc] init];

    label.attributedText = attributedText;
    label.numberOfLines = 0;
    label.lineBreakMode = NSLineBreakByWordWrapping;
    CGSize size = [label sizeThatFits:CGSizeMake(desiredWidth, CGFLOAT_MAX)];

    font = nil;
    attributedText = nil;

    return MAX(44, size.height + 22);//top + bottom padding
}

然后在我的表格中我打电话

 - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [MyCell cellHeightForTitle:@"Some long title"];
}