创建单个大小的动态UILabel字体
我们都知道如何创建动态UILabel字体(单行) -
We all know how to create dynamic UILabel font(Single Line) -
lbl.adjustsFontSizeToFitWidth = true
lbl.numberOfLines = 1
lbl.minimumScaleFactor = 0.1
lbl.baselineAdjustment = UIBaselineAdjustment.AlignCenters
lbl.textAlignment = NSTextAlignment.Center
问题是它为每个给定的字符串提供不同的结果。所以例如,如果我有一个字符串Hello
和Hello World
计算的字体大小将不同。我需要为所有字符串创建单个大小的动态字体。
The problem is that it gives different results for each given string. So for example if i have a string "Hello"
and "Hello World"
the calculated font size will be different.I need to create dynamic font with a single size for all strings.
我的项目示例:
iPhone 6内置相机效果的示例(可以看到所有的UILabels字体大小匹配):
Example from iPhone 6 built in camera effects(As you can see all the UILabels font sizes matches) :
我在想什么?
基本上我知道我会有最大的字符串。所以我想以某种方式计算(以有效的方式)给定的 CGSIze 中最大字符串的字体大小是什么。所以它将永远保持在边界。 任何建议?
Basically I know what is the largest string i'll have. So i was thinking somehow calculate(in a effective way) what would be the font size for the largest string in the given CGSIze. So it will always stay in bounds. Any suggestions?
你是一个说法:
lbl.minimumScaleFactor = 0.1
线意味着,嘿,iOS,如果你觉得缩小字体,请继续缩小。如果你不想要的话,那就不要这么说了。
That line means, "Hey, iOS, if you feel like shrinking the font, go ahead and shrink it." If you don't want that, then don't say that.
相反,选择一个字体大小并坚持下去。什么尺寸?那么NSString可以告诉你一个给定字体/大小的绘制字符串的大小。所以只要把你最长的字符串和循环不同的大小,直到找到一个适合所需的空间。
Instead, pick a font size and stick to it. What size? Well, NSString has the ability to tell you the size of a drawn string in a given font/size. So just take your longest string and cycle through different sizes until you find one that fits in the desired space.
将你自己的值插入到这个:
Plug your own values into this:
func fontSizeToFit(s:String, fontName:String, intoWidth w:CGFloat) -> CGFloat? {
let desiredMaxWidth = w
for i in (8...20).reverse() {
let d = [NSFontAttributeName:UIFont(name:fontName, size:CGFloat(i))!]
let sz = (s as NSString).sizeWithAttributes(d)
if sz.width <= desiredMaxWidth {
return(CGFloat(i))
}
}
return nil
}
print(fontSizeToFit("Transferation", fontName:"GillSans", intoWidth:50)) // 9.0
(以前是一个优雅的字符串绘图功能,可以让字体缩小和 NSString会告诉你如何很多,它缩小到适合;但这个功能是破碎的,唉,所以我不能建议你使用它。)
(There used to be an elegant string drawing feature where you could let the font shrink and NSString would tell you how much it shrank to fit; but that feature is broken, alas, so I can't advise you to use it.)