问题
I'm a bit new in Swift, and I need some help with this:
I have a UILabel inside a UIView, and this label can receive any ammount of text. So I want to resize the UILabel based on the text it receives, and also resizes its container, the UIView. The UILabel must have a max width but not max height. It is very similar to what happens in Whatsapp with a message text (his green container grows accordly the text inside).
I believe it is about auto layout, but I really can't understand most of it.
EDIT: Create dynamically.
Can anyone help me?
回答1:
The UIView that contains the Label should not have a fixed height then. Just add constraints to set the UIView width and the X/Y coordinates.
Inside it the UILabel should have fixed constraints to Top/Bottom and Right/Left to the UIView and also set it's numberOfLines to 0
With these constraints the container View will expand to adjust the height based on the text.
See attached Screenshots
Adding Container View Constraints (notice no bottom or height constraint added)
Adding Label Constraints (fixed constraints to all UIView Edges)
Result with short text
Result with long text
回答2:
@Lefteris' answer is correct. No need to define the width and height of the containing view. You just need to contraint it in its parent edges, then constraint the label inside it in the containing view's edges.
Here is how I did it in code.
let containingView: UIView = UIView()
containingView.translateAutoresizingMaskIntoConstraints = false
addSubview(containingView)
let labelInside: UILabel = UILabel()
labelInside.translateAutoresizingMaskIntoConstraints = false
containingView.addSubview(labelInside)
NSLayoutConstraint.activate([
//in my case, i want my containingView on the top left corner of the superView.
containingView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
containingView.topAnchor.constraint(equalTo: contentView.topAnchor),
labelInside.leadingAnchor.constraint(equalTo: containingView.leadingAnchor),
labelInside.trailingAnchor.constraint(equalTo: containingView.trailingAnchor),
labelInside.topAnchor.constraint(equalTo: containingView.topAnchor),
labelInside.bottomAnchor.constraint(equalTo: containingView.bottomAnchor)
])
Now if you want to have some margins / insets in your label, you can just add a constant when defining the constraints. :) HTH
回答3:
Below property works for me,hope this will helps
[label sizeToFit];
来源:https://stackoverflow.com/questions/49934650/swift-how-to-resize-a-uiview-based-on-its-uilabel-size-that-is-inside