Search code examples
iosswiftuikituilabel

How can you find the height of a label that is "sizeToFit"?


I have a label containing strings of variable size. The label is embedded in a vertical stack of a fixed width.

   var productName: UILabel = {
        let lbl = UILabel()
        lbl.translatesAutoresizingMaskIntoConstraints = false
        lbl.numberOfLines = 0
        lbl.sizeToFit()
        lbl.textColor = .black
        lbl.font = UIFont(name: "HelveticaNeue", size: 13)
        lbl.textAlignment = .center
        return lbl
    }()


    var Vstack: UIStackView = {
        let stack = UIStackView()
        stack.axis = .vertical
        stack.alignment = .center
        return stack
    }()

I need the height of this label after inserting text into it because it dictates the size of a tableViewCell it is in. As the string it contains is variable and the label itself is "sizeToFit", I have been unable to calculate its height with the first things that came to mind:

productName.frame.height 
productName.frame.size.height
productName.layer.frame.height

Is there any way to get the height of a label after inserting text into it?


Solution

  • You can use intrinsicContentSize which returns the CGSize of the label text the UILabel element,

    You can read more about it in this article: intrinsicContentSize