uikitautoresizingmask

Why does label need sizeToFit?


If sizeToFit is not called, the label is invisible. Why is this?

class RootViewController: UIViewController {

    override func loadView() {

        let v = UIView()

        v.backgroundColor = .green

        self.view = v

        let label = UILabel()
        v.addSubview(label)
        label.text = "Hello, World!"

        label.autoresizingMask = [
            .flexibleTopMargin,
            .flexibleLeftMargin,
            .flexibleBottomMargin,
            .flexibleRightMargin]
        label.sizeToFit()
        label.center = CGPoint(v.bounds.midX, v.bounds.midY)
        label.frame = label.frame.integral
    }

}

Solution

  • UIView() is the same thing as UIView(frame: CGRect.zero). So the default size of your label is zero. You're using manual layout, which means that the system won't automatically resize your label. So whatever size you assign to it is the size it will have. Your code isn't assigning a size anywhere except for the call to sizeToFit(). So if you don't call sizeToFit(), your label will retain the zero size that you created it with. sizeToFit() changes its size to fit its contents, so you can actually see it.