创建单个大小的动态UILabel字体 [英] Create single size dynamic UILabel font

查看:167
本文介绍了创建单个大小的动态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

问题是它为每个给定的字符串提供不同的结果。所以例如,如果我有一个字符串HelloHello 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.

我的项目示例:

< a href =https://i.stack.imgur.com/KLE1Z.png =nofollow noreferrer>

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

这篇关于创建单个大小的动态UILabel字体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆