Phyber
Phyber

Reputation: 1368

Swift: scrollview autolayout

I need to display some information in a scrollview and it should look like this:

enter image description here

First view has defined height but second one has dynamic height. I know how to make it dynamic but I don't know how to make it in scroll view. It tried to do it but it doesn't work. Any idea how to make this scene in a scrollview ?

Without scrollview:

enter image description here

Inside. scrollview:

enter image description here

Upvotes: 2

Views: 373

Answers (3)

Ashley Mills
Ashley Mills

Reputation: 53082

If your view is vertically scrolling only, you should use a UITableView rather than a UIScollView

Each of the distinct views in your table would be a UITableViewCell. For each cell set auto layout constraints for the contents, ensuring your constraints are attached to the top and bottom of the cell's content view. To make it even easier, consider using UIStackViews inside your cells.

Then in your table view controller…

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = <estimate of height>

… and your cells will resize themselves.

There are plenty of resources out there for autosizing table view cells…

Upvotes: 2

NotABot
NotABot

Reputation: 526

Your second view or label inside that view should not have a Height constraint.

For that Label, set number of lines to '0' and don't give it a height. But if it gives warning that second view requires Height constraint then give it a Height constraint with Low priority.

Upvotes: 0

Salil Junior
Salil Junior

Reputation: 424

Hard to give a definitive answer without more details... Based on info you gave I'd give the following generic solution:

Assuming you are using StroyBoard / Xib to design your view - Then you could setup your view as below:

-View (root view)

   -ScrollView

      -UIStackView (vertical stackview)

         -UIView (set static height and add all other components)

         -UILabel (dynamic label ie with No. of lines set to 0)

         -UIView (another view with static height set)

After... - using autlayout set the top, leading, trailing, bottom constraints for UIScrollView to the root view... - using autolayout set the top, leading, trailing, bottom constraints for your UIStackView to those of the scrollview... - using autolayout set the width of your UIStackView - you can make it to be equal to that of the root view but also you could give it any width you desire - using autolayout EITHER center your UIStackView on the Y axis (vertically) or set its top constraint to that of the root UIView as it needs to know its Y position...

With this, you should have your scrollview kicking in when the size of your content becomes larger than the screensize

If this is not what you are looking for then you'll have to provide more info or give clarification.

Upvotes: 0

Related Questions