The result of the following code is: I don't see the label.
My understanding was that the intrinsicSize of the label would allow the label to stretch . Why isn't that happening?
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(label)
}
let label : UILabel = {
let label = UILabel()
label.text = "How are you doing today my friend"
label.backgroundColor = .orange
return label
}()
}
This:
creates a label at
(0, 0)
with width0
and height0
. By default, iOS will create constraints from theframe
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):
Or you can use the
label.intrisicContentSize
when you create frame:Note: If you use
label.intrinsicSize
to set theframe
, theframe
will not change when you change the label text. You'd have to update it again with: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 theframe
, so they have no effect. By disabling the creation of constraints from theframe
, you give the lower priorityinstrinsicContentSize
constraints an opportunity to affect the layout of theUILabel
.You can read about this in more detail in Apple's Auto Layout Guide in the section entitled Intrinsic Content Size.
It's Intrinsic content size not Intrinsic content position guarantee to give a width and height for the label If it's not rigidly have leading and trailing constraints that may trim it's content , but at least you must give the label x,y position either by frame layout or auto layout but to set