guide for UIScrollView and autolayout

2019-08-01 15:25发布

I am struggling with UIScrollView and AutoLayout. I read a blog and tried to do my own stuff. However, Xcode is reporting ambiguous content size. I setup the scrollview and leading, trailing, top, bottom constraints to 0 from super view.

There is a UIView as container to hold all of my sub views, including two UILabel elements and two UICollectionView views. I set the container view as equal width and equal height with the View controller's view. Then I set the UILabel and UICollectionView views constraints all to 0. However it runs as the below picture.

Please help me or give me some doc or guide on UIScrollView and AutoLayout.

The constraints

problems

screnshot

1条回答
够拽才男人
2楼-- · 2019-08-01 16:09

Your main issue is that the contents of the scrollView (i.e. your container view) are not pinned to the scrollView.

Here is what I suggest:

1) Remove the constraints for the width and height of your container view.

2) Pin the container view's left, top, right, and bottom to the scrollView's left, top, right, and bottom. By doing this, however big your container view is, that will define the scrollable area of the scrollView.

3) If you just want your content to scroll vertically, constrain the width of the container view to the scrollView's width.

4) You'll need to specify the container view's height. You can do this by just giving it a fixed height constraint. Make sure it is bigger than the scrollView height, or there will be nothing to scroll. The other way to do it is to make sure that its content views sizes are fully specified and that the top most view inside the container view is pinned to the top of the container view, and the bottom most view in the container view is pinned to the bottom, and the views should be pinned to each other vertically. In other words, you should have enough constraints inside your container view for Auto Layout to be able to compute the height of your container view.

查看更多
登录 后发表回答