【问题标题】:How can I trim the height of UILabel to perfectly fit the text without ever changing font size?如何在不改变字体大小的情况下修剪 UILabel 的高度以完全适合文本?
【发布时间】:2015-08-08 19:38:19
【问题描述】:

这是我的 UILabel(由黄色部分定义):

这是在我将 [shortDescriptionLabel sizeToFit]; 添加到代码末尾之后:

这是第二个示例(显示在 sizeToFit 之后字体大小实际上发生了变化:

这是我添加 [shortDescriptionLabel sizeToFit];到我的代码结尾(很明显,字体大小恢复为 30.0):

我想修剪多余的高度(胡萝卜上方和下方)。我怎样才能做到这一点?这是我当前的代码:

    shortDescriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(itemImageView.frame.origin.x+itemImageView.frame.size.width+10, 20, self.tableView.frame.size.width-itemImageView.frame.origin.x-  itemImageView.frame.size.width-20-20, tableViewCellHeight/2)];
    shortDescriptionLabel.text = itemObject.shortDescription;
    shortDescriptionLabel.font = [UIFont boldSystemFontOfSize:30];
    shortDescriptionLabel.textAlignment = NSTextAlignmentCenter;
    shortDescriptionLabel.adjustsFontSizeToFitWidth = YES;
    shortDescriptionLabel.numberOfLines = 0;
    shortDescriptionLabel.minimumScaleFactor = 0;
    [shortDescriptionLabel setBackgroundColor:[UIColor yellowColor]];
    CGFloat fontSize = shortDescriptionLabel.font.pointSize;
    NSLog(@"fontSize = %f", fontSize);

请记住,即使显示的字体大小明显小于 30.0,最后一个 NSLog 将始终显示 30.0(之前设置的字体大小)。

请帮忙。网上似乎有很多关于此的内容,但我似乎无法得到任何工作。

【问题讨论】:

  • 你什么时候打电话给sizeToFit
  • 我尝试在所有内容的末尾添加该行。
  • 显示调用sizeToFit 后标签的样子。确保文本没有换行符或其他空格。
  • maddy 我已经添加了它的外观并提供了第二个示例。我应该提到它是一个多行 UILabel。

标签: ios objective-c uilabel


【解决方案1】:

你可以使用sizeToFit,但如果你想修剪高度并保持宽度,你可以添加一个高度约束等于使用的 UIFont 的lineHeight

【讨论】:

    【解决方案2】:

    自动布局

    1-正确添加它的Leading,Trailing,Top and bottom Constraints并写这行代码就行了

    [label setPreferredMaxLayoutWidth:300.0];
    

    非自动布局

    -(CGSize)m_GetHeight:(NSString*)text 
    {
       CGSize constraintSize=[text sizeWithFont:[UIFont fontWithName:@"Arial" size:15.] constrainedToSize:CGSizeMake(182, 2000) lineBreakMode:NSLineBreakByWordWrapping];
       return constraintSize;
    
    }
    

    【讨论】:

    • 我不太确定设置最大宽度会做什么。我担心身高:S
    • 当您分配 maxwidth 时,它将根据内容大小自动调整其高度。
    • 问题不在于我的宽度。正如您在示例中看到的那样,宽度永远不会超过不应该的位置。
    • 你在使用自动布局吗?
    猜你喜欢
    • 2014-10-07
    • 2013-05-14
    • 2012-06-16
    • 2015-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多