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)
编辑:固定的代码来初始化newFont
用font
.在某些情况下修复崩溃.