具有adjustsFontSizeToFitWidth的多行UILabel

Ort*_*ntz 43 iphone cocoa-touch uikit uilabel ios

我有一个多行UILabel,其字体大小我想根据文本长度进行调整.整个文本应该适合标签的框架而不截断它.

遗憾的是,根据文档,该adjustsFontSizeToFitWidth属性"仅在numberOfLines属性设置为1 时才有效".

我尝试使用确定调整后的字体大小

-[NSString (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode]
Run Code Online (Sandbox Code Playgroud)

然后递减字体大小直到它适合.不幸的是,此方法在内部截断文本以适合指定的大小,并返回生成的截断字符串的大小.

Ort*_*ntz 50

这个问题中,0x90提供了一个解决方案 - 虽然有点难看 - 做了我想要的.具体来说,它正确处理单个单词不适合初始字体大小的宽度的情况.我稍微修改了代码,以便它作为一个类别NSString:

- (CGFloat)fontSizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size {
    CGFloat fontSize = [font pointSize];
    CGFloat height = [self sizeWithFont:font constrainedToSize:CGSizeMake(size.width,FLT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;
    UIFont *newFont = font;

    //Reduce font size while too large, break if no height (empty string)
    while (height > size.height && height != 0) {   
        fontSize--;  
        newFont = [UIFont fontWithName:font.fontName size:fontSize];   
        height = [self sizeWithFont:newFont constrainedToSize:CGSizeMake(size.width,FLT_MAX) lineBreakMode:UILineBreakModeWordWrap].height;
    };

    // Loop through words in string and resize to fit
    for (NSString *word in [self componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]) {
        CGFloat width = [word sizeWithFont:newFont].width;
        while (width > size.width && width != 0) {
            fontSize--;
            newFont = [UIFont fontWithName:font.fontName size:fontSize];   
            width = [word sizeWithFont:newFont].width;
        }
    }
    return fontSize;
}
Run Code Online (Sandbox Code Playgroud)

使用它与UILabel:

    CGFloat fontSize = [label.text fontSizeWithFont:[UIFont boldSystemFontOfSize:15] constrainedToSize:label.frame.size];
    label.font = [UIFont boldSystemFontOfSize:fontSize];
Run Code Online (Sandbox Code Playgroud)

编辑:固定的代码来初始化newFontfont.在某些情况下修复崩溃.

  • 这很棒.为方便起见,我在"UILabel"上添加了对最小字体大小和类别的支持,并为所有感兴趣的人添加了[上传为gist](https://gist.github.com/2766074). (5认同)
  • 我尝试将此转换为iOS 7友好,但我无法得到相同的结果.iOS 7有什么类似的东西吗? (3认同)

wei*_*enw 6

在某些情况下,如果你知道你想要多少行(例如"2"),将"换行"从"自动换行"更改为"截断尾巴"可能就是你所需要的:信用:Becky Hansmeyer