本文介绍了带有 -[sizeWithFont:constrainedToSize:lineBreakMode] 的 UILabel 正在切断单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

UILabel 位于 UITableViewCell 内.在单元格点击时,高度会扩展,第二个 UILabel 出现,其中包含不同数量的数据.

UILabel inside of a UITableViewCell. On cell tap, height expands and a second UILabel appears with various amounts of data.

问题是,如果换行,sizeWithFont:constrainedToSize:lineBreakMode: 不会返回正确的高度并切断底线.

The problem is, if the line wraps, sizeWithFont:constrainedToSize:lineBreakMode: does not return the proper height and cuts off the bottom line.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    labelExpanded = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
    labelExpanded.font = [UIFont boldSystemFontOfSize:11];
    labelExpanded.textAlignment = UITextAlignmentLeft;
    labelExpanded.lineBreakMode = UILineBreakModeWordWrap;
    labelExpanded.numberOfLines = 0;
    [cell.contentView addSubview:labelExpanded];

    CGSize constraint = CGSizeMake(300, 20000);
    CGSize size = [expandedDetails sizeWithFont:[UIFont boldSystemFontOfSize:11] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

    [labelExpanded setText:expandedDetails];
    [labelExpanded setFrame:CGRectMake(16, 30, 248, size.height)];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(// Row is Expanded)
    {
        CGSize constraint = CGSizeMake(300, 20000);
        CGSize size = [sameTextAsLabel sizeWithFont:[UIFont boldSystemFontOfSize:11] constrainedToSize:constraint lineBreakMode:UILineBreakModeWordWrap];

        // I found +8 to height added nice padding
        CGFloat height = size.height + 8;
    }
    else // Row is not expanded
        return 30;
}

相同的文本被提供给两者,它由一个带有多个新行的字符串组成\n.如果线条比宽度长,自动换行会完成它的工作,但在计算其动态高度时,它无法包括换行.

The same text is fed to both, it consists of a string with multiple new lines \n. If the line is longer than width, word wrap does its job but when calculating its dynamic height, it fails to include the wrapped line.

如果我向 [labelExpanded setFrame:height] 添加任何值,例如 [size.height + 30],我的包裹线就会出现.但是,如果该行没有换行,则会添加不必要的空格.

If I add any value to the [labelExpanded setFrame:height] such as [size.height + 30] my wrapped line shows up. However, if the line isn't wrapped, it adds unnecessary whitespace.

我无法在网上找到解决方案.

I haven't been able to find a solution online for this.

推荐答案

我注意到的一件事是,您正在根据宽度 300 计算大小,但将标签大小设置为 248.

One thing I note is that you are calculating the size based on a width of 300, but sizing the label at 248.

这篇关于带有 -[sizeWithFont:constrainedToSize:lineBreakMode] 的 UILabel 正在切断单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 09:17