如何在 iOS 7.0 或更高版本中获得自动调整的字体大小? [英] How do I get auto-adjusted font size in iOS 7.0 or later?

查看:10
本文介绍了如何在 iOS 7.0 或更高版本中获得自动调整的字体大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 UILabel 或 UITextField 中缩小某些文本的字体大小.这在 iOS 7.0 之前是可能的:如何获取 UILabel (UITextView)自动调整字体大小?.但是,sizeWithFont 在 iOS 7.0 中已被弃用.我尝试过使用它的替代品 sizeWithAttributes,但没有成功.在 iOS 7.0 中有没有办法做到这一点?

I want to get the font size of some text after it's been scaled down in a UILabel or UITextField. This was possible before iOS 7.0: How to get UILabel (UITextView) auto adjusted font size?. However, sizeWithFont has been deprecated in iOS 7.0. I've tried using its replacement, sizeWithAttributes, but with no success. Is there any way to do this in iOS 7.0?

推荐答案

Swift 4

上面的答案效果很好,但使用了一些不推荐使用的值/函数.这是一个在 2018 年有效的固定版本.

The answers above work well, but use some deprecated values/functions. Here's a fixed version that works in 2018.

func approximateAdjustedFontSizeWithLabel(_ label: UILabel) -> CGFloat {
    var currentFont: UIFont = label.font
    let originalFontSize = currentFont.pointSize
    var currentSize: CGSize = (label.text! as NSString).size(withAttributes: [NSAttributedStringKey.font: currentFont])

    while currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor) {
        currentFont = currentFont.withSize(currentFont.pointSize - 1.0)
        currentSize = (label.text! as NSString).size(withAttributes: [NSAttributedStringKey.font: currentFont])
    }

    return currentFont.pointSize
}

这篇关于如何在 iOS 7.0 或更高版本中获得自动调整的字体大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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