我有一个多行UILabel,其字体大小我想根据文本长度进行调整.整个文本应该适合标签的框架而不截断它.
遗憾的是,根据文档,该adjustsFontSizeToFitWidth属性"仅在numberOfLines属性设置为1 时才有效".
我尝试使用确定调整后的字体大小
-[NSString (CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode]
Run Code Online (Sandbox Code Playgroud)
然后递减字体大小直到它适合.不幸的是,此方法在内部截断文本以适合指定的大小,并返回生成的截断字符串的大小.
我试图找到适合给定字符串的给定矩形的最大字体大小.该算法的目标是尽可能用尽可能大的字体填充尽可能多的矩形.我的方法 - 从我在网上找到的方法修改 - 做得很好,但它通常不会填满整个矩形.我很想看到如何改进这个算法的一些合作,以便每个人都可以从中受益:
-(float) maxFontSizeThatFitsForString:(NSString*)_string
inRect:(CGRect)rect
withFont:(NSString *)fontName
onDevice:(int)device
{
// this is the maximum size font that will fit on the device
float _fontSize = maxFontSize;
float widthTweak;
// how much to change the font each iteration. smaller
// numbers will come closer to an exact match at the
// expense of increasing the number of iterations.
float fontDelta = 2.0;
// sometimes sizeWithFont will break up a word
// if the tweak is not applied. also …Run Code Online (Sandbox Code Playgroud)