问题
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
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.
Example from my project :
Example from iPhone 6 built in camera effects(As you can see all the UILabels font sizes matches) :
What i was thinking to do?
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?
回答1:
You are the one saying:
lbl.minimumScaleFactor = 0.1
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.
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
(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.)
来源:https://stackoverflow.com/questions/33160574/create-single-size-dynamic-uilabel-font