[英]iOS: how to set constraints to UIScrollView
I would like to implement a simple UIViewController
with vertically scrollable content. 我想实现一个具有垂直滚动内容的简单
UIViewController
。
I have been trying to use UIScrollView
, but I am struggling with setting the constraints in Interface Builder. 我一直在尝试使用
UIScrollView
,但是我正在努力在Interface Builder中设置约束。 Can anyone illustrate the proper way to do it? 谁能举例说明这样做的正确方法?
Let's consider a page which has a UILabel
with a long text and a couple of UIImageView
s placed at the bottom of the text. 让我们考虑一个页面,该页面的
UILabel
带有长文本,并且在文本底部放置了两个UIImageView
。
UIScrollView
has 2 important properties when dealing with autolayout
constraint and scrolling function. 在处理自动
autolayout
约束和滚动功能时, UIScrollView
具有2个重要属性。 Those are size and content size. 这些是大小和内容大小。
UIScrollView
size is the size of UIScrollView
related to its superview. UIScrollView
大小是与其超级视图相关的UIScrollView
的大小。 You can set its constraint by pin each of top, trailing, leading, bottom to its superview. 您可以通过将其顶部,尾部,前导,底部固定到其超级视图来设置其约束。
UIScrollView
content size on the other hand is the size of UIScrollView
subview related to it. 另一方面,
UIScrollView
内容大小是与其相关的UIScrollView
子视图的大小。 It is basically the scrollable size. 基本上是可滚动的大小。 Setting the constraint of its subview is a little bit tricky, you can't just pin each side of each subview to
UIScrollView
. 设置其子视图的约束有些棘手,您不能仅将每个子视图的每一侧固定到
UIScrollView
。 You also need to add some height and width constraint to it so it won't give ambiously constraint warning. 您还需要向其添加一些高度和宽度约束,以免产生明显的约束警告。
Let's say for example that you have one UILabel
and one UIImageView
below the label. 例如,假设您在标签下方有一个
UILabel
和一个UIImageView
。
A simple way to create vertically scrollable content would be: 创建垂直可滚动内容的简单方法是:
UILabel
to UIScrollView
UILabel
顶部,前导,尾随空间约束设置为UIScrollView
UILabel
height and width constraint UILabel
高度和宽度约束 UIImageView
top constraint to UILabel
UIImageView
顶部约束设置为UILabel
UIIMageView
trailing, leading and bottom space constraint to UIScrollView
UIIMageView
尾部,前部和底部空间约束设置为UIScrollView
UIImageView
height and width constraint UIImageView
高度和宽度约束 UILabel
height constraint based on the text and call layoutIfNeeded
UILabel
高度约束并调用layoutIfNeeded
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.