eivindml
eivindml

Reputation: 2520

Auto resize UIView based on multi line UILabel

Problem: I have a custom view with a multi-line UILabel (se picture below).

enter image description here

This custom view is then added to a screen in my storyboard (se picture below).

enter image description here

This works great. The problem is that the multi-line label will change dynamically a few times under execution, and then the blue UIView box won't fit. It's also a problem with smaller/bigger screen size.

Question: So how do I get the UIView to automatically resize in height according to the height of the UILabel? Is it possible to do through Interface Builder and Autolayout? (not nececery, but most of my other settings are done through IB)

Let me know if there is more details needed.

Upvotes: 1

Views: 3970

Answers (1)

Arthur Shinkevich
Arthur Shinkevich

Reputation: 801

As long as you make sure that labels in your custom view are pinned to all sides (Title Label pinned to: Leading, Top, Trailing of the superview and Bottom to Content Label; Content Label pinned to: Leading, Bottom, Trailing of the superview and Top to Title Label) you will have your superview change it's height according to the content.

Also, note that your superview won't need a height constraint, just pinning it to the Leading, Bottom and Trailing sides should be sufficient.

I had almost identical view in one of my apps. What I would do to make sure the height changes according to update is this:

customView.setNeedsLayout()
customView.layoutIfNeeded()

You can also wrap this code in UIView.animate(withDuration: ...) block

Cheers!

Upvotes: 3

Related Questions