ZbadhabitZ
ZbadhabitZ

Reputation: 2913

Understanding UIView Height When Constraints Are Set with AutoLayout/UIScrollView

I hope this this graphic helps, but I am trying to wrap my head around a concept. I have a UIScrollView, added to a self.view in my ViewController, with its top, leading, trailing, and bottom edges pinned to that of the self.view. This is viewA.

I have a second UIView, viewB, with several subviews. Each of those subviews are added to viewB with AutoLayout, and for brevity, each of those subviews have a height constraint set to a value.

I want to add viewB to viewA, with viewA able to scroll vertically. Since viewB is undoubtedly taller than viewA, it should scroll.

I am adding viewB like so;

viewB.topAnchor.constraint(equalTo: viewA.topAnchor).isActive = true
viewB.leadingAnchor.constraint(equalTo: viewA.leadingAnchor).isActive = true
viewB.trailingAnchor.cosntraint(equalTo: viewA.trailingAnchor).isActive = true

This is where I am stuck. If I set a bottom anchor (viewB.bottomAnchor.constraint(equalTo: viewA.bottomAnchor).isActive = true), my UIScrollView does not scroll, and viewB is visibly cut off.

If I set a random height for viewB (using viewB.heightAnchor.constraint(equalToConstant: 2000.0).isActive = true), the UIScrollView does scroll, though this constant is far too tall.

I am confused how to get the appropriate height for viewB. Since viewB does have an actual height (with hard-coded subviews), I see no reason that AutoLayout shouldn't be able to calculate that height of viewB, even with no bottom anchor set, but can't figure out the right code.

Upvotes: 0

Views: 314

Answers (2)

chinghoi
chinghoi

Reputation: 13

If the height constraint is complete, you don't have to consider viewA's contentSize. You don't need to use ViewB, subviews add to viewA, subview1's top equalTo viewA's top, set subview1 height, subview1's bottom equalTo subview2's top or offset some Height. And so on. Until the last subview, subview4's bottom equal to viewA' bottom. You can get a suitable content size without setting the height of the content.

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100541

1- You need to hook viewB leading , trailing , top and bottom to viewA , plus width of viewB is set = width of main vc's view

2- all constraints inside viewB should be hooked properly from top to bottom

3- instead of repeatedly using .isActive = true consider wrapping all constraints inside NSLayoutConstraint.activate([<#ConstraintsHere#>])

4- May be for your current approach a UITableView is more suitable

Upvotes: 1

Related Questions