Øyvind
Øyvind

Reputation: 849

UIView dynamic height in Swift and Xcode

In Xcode 7.3 I have the following setup with Auto Layout: enter image description here

When I click the button, I add a UILabel to the Red UIView with addSubview(). What I am trying to achieve is to automatically resize both the red UIView and the green UIView when the size of the combined labels exceeds the red UIView.

I have tried to calculate the size of all the labels, then set the frame.size.height of the red view in didLayoutSubView(), which kinda worked, but then I had trouble when also doing the same with the green UIView, based on the red UIView. It also became very cumbersome when nesting a lot of UIViews. There must be some better way to accomplish this? (without UIStackView).

I have also played around with different Auto Layout settings with no luck. Bonus if this could also be added to a UIScrollView and make the contentSize of that also adjust itself!

All this seems like it should be such a trivial thing to do, so I think I am overlooking something small and easy. Any guidance on how to accomplish this, using Swift and/or Interface Builder would be highly appreciated.

Upvotes: 1

Views: 5036

Answers (2)

BangOperator
BangOperator

Reputation: 4437

When you use addSubview(),

  1. You also need to constrain that label so that the red view know that somebody is trying to expand it.

  2. As i can see you have put correct constraints for and red view in IB. For green view you must only constraints top, leading and training to its superview, and let it expand at bottom so no constraints there, so remove constraint with 480 as constant.

Now when you add a UILabel, make sure you constrain it right pragmatically.

Its is easy to add one UILabel with constraints(constraints for Top,Leading ,Trailing and bottom), but when dynamically we need to add more, we need to play hard with constraints(Removing the bottom constatins of last added label, adding vertical spacing btw last added and the new one, leading trailing and bottom space to container).

We had encounters such a situation in our project so we end up creating a Subclass of UIView in objective c.

NNVerticalStackView.h NNVerticalStackView.m

If you intend iOS9 users only you must use UIStackView introduced in iOS9 APIs.

Upvotes: 1

user4886069
user4886069

Reputation:

You can use UITableView in this case.

1) Add a UILabel in UITableViewCell

2) Set Leading, Trailing, Top and Bottom Constraints to UILabel w.r.t. content view of UITableViewCell

3) Set the number of lines for UILabel to zero

4) Finally, in viewDidLoad() use the following lines of code:

tableView.estimatedRowHeight = 44
tableView.rowHeight          = UITableViewAutomaticDimension

Upvotes: 0

Related Questions