How to check current font size of UILabel?

uilabel adjust font size to fit width
uilabel font size swift
uilabel shrink text to fit
uilabel autoshrink
uilabel font size adjust to fit programmatically swift
adjust uilabel width depending on the text swift
adjustsfontsizetofitwidth storyboard
change text size according to screen ios

I have 3 UILabels and I want to set same (the smallest one from all of 3 possibilities) font for all of them. What is the problem? I don't know how to check the current font - each of UILabels use Autoshrink with minimal font scale and lines amount equaled to 0. The text of UILabels is set in ViewDidLoad() method (there are many combinations of possible label texts).

I tried to get the current font size with UILabel.font.pointSize property (called in viewDidAppear() method) and than compare all of them. The problem is that that UILabel.font.pointSize returns not current value of UILabel text font size (after Autoshrink has been done) but the value that is set in storyboard.

I'm totally out of ideas so thanks for the help!

Greetings, John

This is one way to get the current size of the UILabel pointsize although I know of more ways if this does not work. This is the cleanest and fastest. See example and extension included.

import UIKit

class ViewController: UIViewController {

    lazy var label1 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: 80, width: self.view.bounds.width - 40, height: 40))
        lbl.text = "This is some large text to make it fit to size with a big font size"
        lbl.font = UIFont.systemFont(ofSize: 50, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()

    lazy var label2 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: label1.frame.maxY + 5, width: self.view.bounds.width - 40, height: 40))
        lbl.text = "This is one line"
        lbl.font = UIFont.systemFont(ofSize: 20, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()

    lazy var label3 : UILabel = {
        let lbl = UILabel(frame: CGRect(x: 20, y: label2.frame.maxY + 10, width: self.view.bounds.width - 40, height: 80))
        lbl.text = "This is some large text to make it fit to size with a big font size"
        lbl.font = UIFont.systemFont(ofSize: 100, weight: .bold)
        lbl.textColor = .black
        lbl.minimumScaleFactor = 0.01
        lbl.adjustsFontSizeToFitWidth = true
        lbl.numberOfLines = 0
        return lbl
    }()


    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        self.view.addSubview(label1)
        self.view.addSubview(label2)
        self.view.addSubview(label3)

        var minSize : CGFloat = .greatestFiniteMagnitude
        for sub in self.view.subviews{
            if let lbl = sub as? UILabel{
                //get the size
                let font = lbl.adjustedFont()
                print("the size is \(font.pointSize)")
                minSize = min(font.pointSize,minSize)
            }
        }
        print("the minimum for all fonts is \(minSize)")
        print("i am going to delay for 3 seconds and then reset all the labels to the minimum size :)")
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3.0) {
            for sub in self.view.subviews{
                if let lbl = sub as? UILabel{
                    lbl.font = lbl.font.withSize(minSize)
                }
            }
        }
    }
}
extension UILabel{
    func adjustedFont()->UIFont {
        guard let txt = text else {
            return self.font
        }
        let attributes: [NSAttributedString.Key: Any] = [.font: self.font]
        let attributedString = NSAttributedString(string: txt, attributes: attributes)
        let drawingContext = NSStringDrawingContext()
        drawingContext.minimumScaleFactor = self.minimumScaleFactor
        attributedString.boundingRect(with: bounds.size,
                                      options: [.usesLineFragmentOrigin,.usesFontLeading],
                                      context: drawingContext)

        let fontSize = font.pointSize * drawingContext.actualScaleFactor
        return font.withSize(CGFloat(floor(Double(fontSize))))
    }
}

Example in Action

How to get the current font size of an UILabel, Then to get the font name and size all you need is NSString *fontName = self.​label.font.fontName; CGFloat fontSize = self.label.font.pointSize;. Answers: You can do it like this: label.font = UIFont (name: label.font.fontName, size: 20) Or you can do it like this: label.font = label.font.fontWithSize (20) This will use the same font. 20 can be whatever size you want of course.

What I've found is that inside viewDidLoad() your constraints are not fully defined yet. You can try to do these calculations in another method for example viewWillAppear() or any other that suits you and is executed after viewDidLoad().

ios - How to check current font size of UILabel?, This is one way to get the current size of the UILabel pointsize although I know of more ways if this does not work. This is the cleanest and  Hi. I have a UILabel of a fixed size. This size cannot be changed, as the interface is all set up to have that label there at that particular size. I'm trying to get the largest font size for any font I might put in that label, that will fit all of the text inside that label.

use this extention

extension String {

       func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
            let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
            let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

            return ceil(boundingBox.height)
        }
}

get height

height = strDesc.height(withConstrainedWidth: UIScreen.main.bounds.size.width - 160, font: UIFont.systemFont(ofSize: 14.0))

font, Declaration. var font: UIFont! { get set } The default value for this property is the system font at a size of 17 points (using the systemFont(ofSize:) class method of  When the label has its size completely defined externally, you can specify how it handles the situation when its content doesn’t fit within the bounds. To reduce the font size, set the adjusts Font Size To Fit Width property to true and set the minimum Scale Factor property to a value between 0 and 1. The latter of these properties represents how much smaller than the requested font size the label scales the text.

adjustsFontSizeToFitWidth, var adjustsFontSizeToFitWidth: Bool { get set } property exceeds the label's bounding rectangle, the label reduces the font size until the text fits or it has scaled the font down to the minimum font size. The default value for this property is false . The label is clipped because the current label size is too small for the new text at the new font size. Determine the current label size by getting the third and fourth elements of the Position property value. size = lbl.Position(3:4) size = 31 15

iOS, iOS Get UILabel's size strictly based on its text and font. Example#. NSString provides method boundingRectWithSize which can be used to predict the resulting  UIFont has some properties for font metrics (line height, ascender, descender, etc.) that you could use to determine the right font size for a given height. It may be tedious, but it's possible. I don't know of a better way.

Adaptive trick for label font size - Elsayed Hussein, Adaptive trick for label font size How to default UILabel Font and Size using Swift Check my app Bokhary — Phrase Keyboard. A font is often measured in pt ( points ). Points dictate the height of the lettering. There are approximately 72 (72.272) points in one inch or 2.54 cm. For example, the font size 72 would be about one inch tall, and 36 would be about a half of an inch. The image shows examples of font sizes ranging from 6 pt to 84 pt. In computing, font sizes

Comments
  • did you try to assign the UIFont property directly? label2.font = label1.font?
  • Yes. I mean even when I do print of myLabel.font.pointSize I get value from Storyboard which is definitely to big to be real value (and it's same for 3 labels which have visually different font sizes).
  • Yes, definitely it's solution of my problem, thanks a lot agibson007!
  • @Janoz also in the extension the scaleFactor should be the label.minimumScaleFactor. I need to fix that
  • Aff, my bad, I wrote bad in the stack post. I called this in viewDidAppear ofc, but thanks a lot. ;)