This:
let label = UILabel()
creates a label at (0, 0)
with width 0
and height 0
. By default, iOS will create constraints from the frame
for the position, width, and height of the label.
If you want to use the intrinsic size of the label, disable the creation of constraints from the frame and give the label constraints to place it in the view.
For example (after adding the label as a subview):
label.translatesAutoresizingMaskIntoConstraints = false
label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
Or you can use the label.intrisicContentSize
when you create frame:
label.frame = CGRect(origin: CGPoint(x: 40, y: 100), size: label.intrinsicContentSize)
Note: If you use label.intrinsicSize
to set the frame
, the frame
will not change when you change the label text. You'd have to update it again with:
label.frame.size = label.intrinsicContentSize
after changing label.text
.
In reality, Auto Layout creates 4 constraints for a label's instrinsicContentSize
, but these constraints are at a lower priority than the constraints created from the frame
, so they have no effect. By disabling the creation of constraints from the frame
, you give the lower priority instrinsicContentSize
constraints an opportunity to affect the layout of the UILabel
.
You can read about this in more detail in Apple's Auto Layout Guide in the section entitled Intrinsic Content Size.
translatesAutoresizingMaskIntoConstraints
tofalse
I still get the same result... – Flores