-ViewController
--View
---ScrollView (Top,Bottom,Leading,Trailing spaces to superview set to 0)
----ContentView (Top,Bottom,Leading,Trailing spaces to superview set to 0, Width equals with View (ViewController's child))
-----Label1
-----etc...

如果我为我的内容视图设置了特定的高度限制(例如1000),ScrollView可以正常工作,但我得到的静态ContentView为1000,这不是我的目标,因为我的ContentView获得了动态内容,所以它应该是内容所需的高度.

如果删除ContentView的高度约束,Xcode会显示:

Missing Constraints:
ScrollView need constraints for: Y position or height

ScrollView实际上固定在顶部和底部,所以我不知道为什么Xcode want是ScrollView的高度限制...

当我希望ContentView的高度是内容所需的高度时,正确的方法是什么?

推荐答案

Whenever using ScrollView with auto layout always follow below steps,

  1. ScrollView约束:从leadingSpace、topSpace、TrailingSpace、bottomSpace到superView,并确保在控制拖动以添加约束时,按alt添加约束,以便设置约束时不留边距.

  2. 在滚动视图中添加UIView作为容器视图,并设置其约束:

  3. 在这个容器视图中添加的任何视图都必须具有从上到下的约束,而所有视图都应该具有垂直约束,因此containerView可以根据其内部的内容计算自身所需的高度.

如果约束设置正确,则scrollView将根据其内部的组件自动设置其内容大小,您无需手动设置内容大小,而且scrollView仅在容器视图中的组件不适合内部时才会滚动,否则不会滚动.如果你想让它以任何方式滚动,那么你需要从情节提要中判断"垂直反弹"属性以获得反弹效果.

Note: While you set constraint to the component inside the scrollView, you will see the constraint warning till you set the constraint from top component to the bottom one, aways remember that your top component should have top constraint (Vertical constraint) to superView and the component at the bottom should have bottom space constraint to the super view. When this satisfy then all warning will disappear eventually.

滚动视图约束:

enter image description here

ContainerView约束:

enter image description here

Objective-c相关问答推荐

如何使用 iOS 7 SpriteKit 粒子向非游戏的 iOS 应用程序添加粒子效果?

Objective C中的简单字符串连接

将类作为参数传递?

iOS UIImageView 缩小图像在 iPad 2 上产生锯齿图像

定义缓存变量时在objective-c中使用static关键字

如何更改图像 tintColor

避免NSArray 在被枚举时发生Mutations

Objective-C 中的 const 与静态 NSStrings

如何将日期字符串解析为 iOS 中的 NSDate 对象?

了解按位与运算符

未知类型名称类;您指的是 'Class' 吗?

将块存储在数组中

从 NSMutableString 中删除最后一个字符

如何在 Objective-C 中将 NSString 解析为 BOOL?

无法在导航栏中心设置titleView,因为返回按钮

为什么使用弱指针进行委托?

如何在没有死锁的情况下同步调度主队列?

带有Go按钮而不是返回的 iOS 键盘

有没有办法在用户已经在 iOS 上拒绝相机访问权限后向他们询问?

如何在对象内使用 objc_setAssociatedObject/objc_getAssociatedObject?