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

查看:464
本文介绍了如何在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?

推荐答案

这是我为获取UILabel的调整字体大小而制作的函数:

Here's a function I made to get the adjusted font size of a UILabel:

Swift

func getApproximateAdjustedFontSizeWithLabel(label: UILabel) -> CGFloat {

    if label.adjustsFontSizeToFitWidth == true {

        var currentFont: UIFont = label.font
        let originalFontSize = currentFont.pointSize
        var currentSize: CGSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])

        while currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor) {
            currentFont = currentFont.fontWithSize(currentFont.pointSize - 1)
            currentSize = (label.text! as NSString).sizeWithAttributes([NSFontAttributeName: currentFont])
        }

        return currentFont.pointSize

    }
    else {

        return label.font.pointSize

    }

}

Objective-C

- (CGFloat)getApproximateAdjustedFontSizeWithLabel:(UILabel *)label {

    if (label.adjustsFontSizeToFitWidth) {

        UIFont *currentFont = label.font;
        CGFloat originalFontSize = currentFont.pointSize;
        CGSize currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];

        while (currentSize.width > label.frame.size.width && currentFont.pointSize > (originalFontSize * label.minimumScaleFactor)) {
            currentFont = [currentFont fontWithSize:currentFont.pointSize - 1];
            currentSize = [label.text sizeWithAttributes:@{NSFontAttributeName : currentFont}];
        }

        return currentFont.pointSize;
    }
    else {

        return label.font.pointSize;
    }
}

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

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