-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 可以正常工作,但我得到了 1000 的静态 ContentView,这不是我的目标,因为我的 contentView 有动态内容,所以它应该是内容需要的高度.
If i set a specific height constraint for my content view (e.g. 1000) the ScrollView works fine, but i got a static ContentView of 1000, which is not my goal, because my contentView got dynamic content, so it should be the height the content needs.
如果我删除 ContentView 的高度限制,Xcode 会说:
If i delete the height constraint for my ContentView, Xcode says:
Missing Constraints:
ScrollView need constraints for: Y position or height
ScrollView 实际上是固定在顶部和底部的,所以我不知道为什么 Xcode 想要对 ScrollView 进行高度限制...
ScrollView is actually pinned at top and bottom, so i don't know why Xcode want's a height constraint for the ScrollView...
当我希望 ContentView 高度成为内容所需的高度时,正确的方法是什么?
What is the right way to go, when i want the ContentView height to be the height the content needs?
每当使用带有自动布局的 ScrollView 时,请始终遵循以下步骤,
ScrollView 约束:leadingSpace、topSpace、TrailingSpace、bottomSpace 到 superView 并确保当你控制拖动添加约束时,通过按 alt 添加它,这样约束将被设置为无边距.
ScrollView constraints: leadingSpace, topSpace, TrailingSpace, bottomSpace to superView and make sure when you control drag to add constraint, add it by pressing alt so that the constraint would be set without margin.
在滚动视图中添加 UIView 作为容器视图并设置其约束:leadingSpace、topSpace、trailingSpace、bottomSpace 到 ScrollView 而不按 alt 按钮,将 equalWidth 设置为 ScrollView.
Add UIView inside scroll view as container view and set its constraints: leadingSpace, topSpace, trailingSpace, bottomSpace to ScrollView without pressing alt button and set equalWidth to ScrollView.
你在这个容器视图中添加的任何视图都必须具有从上到下的约束,即所有视图都应该具有垂直约束,因此 containerView 可以根据其中的内容计算自身所需的高度.
Whatever views you add inside this container view must have top to bottom constraint that is all view's should have vertical constraint, so containerView can calculate height required for itself based on the content inside it.
如果约束设置正确,则 scrollView 将根据其中的组件自动设置其内容大小,您无需手动设置内容大小,而且只有容器视图内的组件为不适合里面,否则它不会滚动.如果你想让它滚动,那么你需要检查情节提要中的 Bounces Vertically 属性以获得反弹效果.
If the constraints are set correctly then the scrollView will set its content size automatically based on the component inside it and you do not need to set the content size manually, also the scrollView will only scroll if the component inside the container view is not fitting inside otherwise it won't scroll. If you want to make it scroll anyways then you need to check the Bounces Vertically property from storyboard to get the bounce effect.
注意: 当你在 scrollView 中为组件设置约束时,你会看到约束警告,直到你将约束从顶部组件设置到底部组件,记住你的顶部组件应该对 superView 具有顶部约束(垂直约束),并且底部的组件应该对超级视图具有底部空间约束.当这个满足时,所有的警告最终都会消失.
ScrollView 约束:
ScrollView constraints:
ContainerView 约束:
ContainerView constraints:
这篇关于iOS ScrollView 需要约束 y 位置或高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!