的开发者, 我在界面生成器(Xcode 5 / iOS 7)中的自动布局遇到了麻烦。 这是非常基础和重要的,所以我认为每个人都应该知道这是如何正确工作的。如果这是Xcode中的一个bug,那它就是一个严重的bug !

所以,每当我有这样的视图层次结构时,我就会遇到麻烦:

>UIViewController
>> UIView
>>>UIScrollView
>>>>UILabel (or any other comparable UIKit Element)

UIScrollView有固定的约束,例如,每边50px(没问题)。 然后我添加一个顶部空间约束UILabel(没有问题)(我甚至可以钉标签的高度/宽度,改变什么,但应该是不必要的,由于标签的内在大小)

当我给UILabel添加一个尾随约束时,问题就开始了:

例如,尾随空间到:Superview等于:25

现在出现了两个警告——我不明白为什么:

A)滚动内容大小不明确(滚动视图具有不明确的滚动内容高度/宽度)

B)视图错位(Label Expected: x= -67 Actual: x= 207)

我在一个新项目中做了这个最小的例子,你可以下载,我附上了一张截图。如你所见,Interface Builder期望Label位于UIScrollView的边界之外(橙色虚线矩形)。用解决问题工具更新标签的框架,将其移到那里。

请注意:如果你用一个UIView替换UIScrollView,行为是预期的(标签的帧是正确的,根据约束)。所以看起来要么是UIScrollView有问题,要么是我错过了一些重要的东西。

当我运行应用程序而不更新标签的框架时,它的位置很好,正是它应该在的地方,UIScrollView是可滚动的。 如果我确实更新了帧,标签就会从视野中消失,UIScrollView也不会滚动。

帮帮我,欧比王·克诺比!为什么是模棱两可的布局?为什么会出现这种错位的观点?

你可以在这里下载示例项目,试着看看你能弄清楚发生了什么: https://github.com/Wirsing84/AutoLayoutProblem


当前回答

我想这是10秒后的作品。我在XCode 7.3中观察到它,并制作了一个视频。检查:

https://www.youtube.com/watch?v=yETZKqdaPiI

你所要做的就是给UIScrollView添加一个宽度和高度相同的子视图。然后选择ViewController并按下Reset到建议的约束。为了更清楚地理解,请查看视频。

谢谢

其他回答

我终于明白了,我希望这更容易理解。

你通常可以通过添加一个基本的UIView到滚动视图作为一个“内容视图”来绕过这个警告,就像他们提到的,让它和你的滚动视图一样大,在这个内容视图上,设置这6个参数。

如您所见,您总共需要6个参数!哪一个在正常情况下,你复制了两个约束,但这是避免故事板错误的方法。

在我的情况下,我收到了不正确的内容大小和内容大小模糊的问题在iPad,但在iPhone的情况下工作。我在故事板中做了以下更改来解决这个问题。

在UIView中添加scrollview并添加约束前置,上,后,下到0,0,0,0。 设置滚动视图的高度根据要求,例如。One hundred. 添加UIView到滚动视图,并添加约束领先,顶部,尾部和底部0,0,0,0和对齐中心(X)和中心(Y)约束。 在滚动视图的尺寸检查器中取消选择“内容布局指南”。

我知道我可能晚了,但是下一个解决方案无需额外的代码就解决了这类问题,只是使用故事板:

对于你的内容视图,你需要设置前/后/上/下空格到滚动视图的约束,这不会改变内容视图框架,如下所示:

当然,您需要为内容视图创建额外的约束,以便滚动视图可以知道内容大小。例如,设置固定高度和中心x。

希望这能有所帮助。

Xcode 11 +。

使用自动布局的最简单方法:

Add UIScrollView and pin it 0,0,0,0 to superview (or your desired size) Add container of UIView type inside ScrollView, pin it 0,0,0,0 to all 4 sides and center it horizontally and vertically. In size inspector of container, change bottom and align center Y priority to 250. (for horizontal scroll change trailing and align center X) Add all views that you need into said container (UIView). Don't forget to set the bottom constraint on the lowest view. Select the UIScrollView, select the size inspector and deselect Content Layout Guides.

This error took me a while to track down, initially I tried pinning the ScrollView's size but the error message clearly says "content size". I made sure everything I pinned from the top of the ScrollView was also pinned to the bottom. That way the ScrollView can calculate its content height by finding the height of all the objects & constraints. This solved the ambiguous content height, the width is pretty similar... Initially I had most things X centered in the ScrollView, but I had to also pin the objects to the side of the ScrollView. I don't like this because the iPhone6 might have a wider screen but it will remove the 'ambiguous content width' error.