Variable height using constraints

suggest change

You can make a UILabel with a dynamic height using Auto Layout.

You need to set numberOfLines to zero (0) and add a minimum height by setting up a constraint with a relation of .GreaterThanOrEqual on the .Height attribute. Both samples use pre-Swift 4 names (.Height, constraintGreaterThanOrEqualToConstant, .active).

Swift

label.numberOfLines = 0

let heightConstraint = NSLayoutConstraint(
    item: label,
    attribute: .Height,
    relatedBy: .GreaterThanOrEqual,
    toItem: nil,
    attribute: .NotAnAttribute,
    multiplier: 0,
    constant: 20
)

label.addConstraint(heightConstraint)

Swift

label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.heightAnchor.constraintGreaterThanOrEqualToConstant(20).active = true

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents