Honey Honey - 10 months ago 378
Swift Question

How does addSubview work with intrinsicSizes?

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
}()
}

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download