Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

uikit - How do I get auto-adjusted font size in iOS 7.0 or later?

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?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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;
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...