简体   繁体   English

iOS:如何为UIScrollView设置约束

[英]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: 创建垂直可滚动内容的简单方法是:

  1. set top, leading, trailing space constraint of UILabel to UIScrollView UILabel顶部,前导,尾随空间约束设置为UIScrollView
  2. set UILabel height and width constraint 设置UILabel高度和宽度约束
  3. connect height constraint to code so you can modify its value. 将高度约束连接到代码,以便您可以修改其值。
  4. set UIImageView top constraint to UILabel UIImageView顶部约束设置为UILabel
  5. set UIIMageView trailing, leading and bottom space constraint to UIScrollView UIIMageView尾部,前部和底部空间约束设置为UIScrollView
  6. set UIImageView height and width constraint 设置UIImageView高度和宽度约束
  7. change UILabel height constraint based on the text and call layoutIfNeeded 根据文本更改UILabel高度约束并调用layoutIfNeeded

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM