1

我在一个单元格中有一个 UILabel,我需要动态更改 UILabel 的高度。所以单元格是一个高度为 44 和标签 240x44 的 xib 文件,标签水平和垂直自动调整大小。字体为 15.0f 大小,系统。行数 = 0,按字换行。

所以我有方法

+ (CGFloat) cellHeightForString: (NSString *) string
{
    CGFloat cellHeight = [string sizeWithFont:[UIFont systemFontOfSize:15.0f] constrainedToSize:CGSizeMake(240.0f, CGFLOAT_MAX) lineBreakMode:NSLineBreakByWordWrapping].height;
    return  cellHeight < 44.0f ? 44.0f : cellHeight;
}

但是单元格的高度有时会更小,因此并非所有文本行都显示在单元格中。不明白我做错了什么..有什么帮助吗?

4

1 回答 1

0

Try this,

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// add your code snippet here
// dynamically change the label height,
       CGSize textSize = {
        200.0,   // limit width
        20000.0  // and height of text area
    };

    CGSize contentSize = [yourText sizeWithFont:[UIFont systemFontOfSize:15.0] constrainedToSize:textSize lineBreakMode:NSLineBreakByWordWrapping];
    CGFloat contentHeight = contentSize.height < 36? 36: contentSize.height; // lower bound for height

    CGRect labelFrame = [yourLabel frame];
    yourLabel.size.height = contentHeight;
    [yourLabel setFrame: labelFrame];
    [yourLabel setText:yourText];
    return cell;
}

Dynamically change the cell height,

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YourCell *currentCell = (YourCell*)[self tableView:tableView cellForRowAtIndexPath:indexPath];

// change hard coded value based on your cell alignment

    int cellLength=[currentCell.yourLabel.text length]/42;
    cellLength = cellLength*22 > 200 ? cellLength*22 : 200;
    CGSize constraint = CGSizeMake((200 - 10), cellLength);
    CGSize size1 = [cellText sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    return 220+size1.height;
}
于 2013-11-07T12:04:43.353 回答