How does addSubview work with intrinsicSizes?

2019-06-13 05:36发布

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

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-06-13 05:54

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.

查看更多
贼婆χ
3楼-- · 2019-06-13 06:05

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

  translatesAutoresizingMaskIntoConstraints to false
查看更多
登录 后发表回答