YellowPillow YellowPillow - 1 year ago 81
Swift Question

Is there a way to programmatically let a UILabel determine its intrinsic content size

I have created a label via and a container view via:

let label = UILabel(frame: CGRectMake(0,0, 50, 50))
label.text = "omnomnom"
let labelView = UIView(frame: CGRectMake(50, 50, 100, 100))
labelView.backgroundColor = UIColor.orangeColor()
label.textAlignment = .Center

But the label text might change so as a result for a longer word the whole thing won't be shown. I was wondering whether there is way to determine the intrinsic content size after the label is added, so that I can use those values to create a container view that is just a little bit bigger than that of the label.

tx2 tx2
Answer Source

You can use sizeToFit to accomplish that. So you only need to add label.sizeToFit() to the end of your label configuration.

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