1.在ViewController中拖入1个UIScrollView,并为其添加约束
约束为上下左右四边与superview对齐

2.在scrollview中,拖入1个UIView,为了便于区分将其设为橙色。

3.为view添加约束
约束为上下左右四边与superview对齐(在这里与scrollview对齐)

添加完这些约束后,我们发现出现了错误,不要理会

4.为view添加宽度约束,本例中,想达到的效果是scrollView可以竖向滚动,不要横向滚动,
因此,可以将view的宽度约束为与scrollView相同

5.接下来为view添加高度约束

对frame进行更新

愉快的发现约束错误已经消失!
为了验证scrollView是否可以正确滑动
我们在scrollView中添加一个兰色的view,添加宽高约束分别为60,500,然后再添加到黄色view(也就是兰色view的superview)的左边距和上边距

至此,约束全部添加完成。需要滚动的内容都可以在黄色view中添加。
点击运行查看效果

可以看到scrollview可以按照预期滑动
最后,全部的约束见下图

UIScrollView添加约束要点:
1.scrollView与scrollView的superview的约束关系用来确定scrollView的frame
2.scrollView中的『contentView』(本例中的兰色view)的约束关系用来确定scrollView的contentInsets
3.contentView的宽度和高度用来确定scrollView的contentSize
理解这3个要点,即可愉快的为scrollView添加约束
(来源:cnblogs.com作者:ashamp)
网友评论