Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
544 views
in Technique[技术] by (71.8m points)

objective c - Create single size dynamic UILabel font

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 :

MyProject

Example from iPhone 6 built in camera effects(As you can see all the UILabels font sizes matches) :

Apple

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...