UIScrollView 子视图未扩展以填充宽度(自动布局)

ori*_*ion 1 cocoa-touch ios autolayout

我正在使用以下代码将视图约束到父 UIScrollView 的左右锚点。

尽管右锚和左锚被设置为 ScrollView 的左锚和右锚,但视图不会扩展以填充滚动视图。

注意:这张图片中的灰色背景是 UIScrollView 的背景,所以我知道它被正确地限制在它的父视图中。

代码:

self.wtfView.translatesAutoresizingMaskIntoConstraints = false
self.wtfView.backgroundColor = UIColor.orange
self.wtfView.topAnchor.constraint(equalTo: self.passwordField.bottomAnchor, constant: 40.0).isActive = true
self.wtfView.leftAnchor.constraint(equalTo: self.containerView.leftAnchor, constant: 40.0).isActive = true
self.wtfView.rightAnchor.constraint(equalTo: self.containerView.rightAnchor, constant: 40.0).isActive = true
self.wtfView.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
self.wtfView.bottomAnchor.constraint(equalTo: self.containerView.bottomAnchor, constant: 40.0).isActive = true
Run Code Online (Sandbox Code Playgroud)

https://imgur.com/a/U88iW

编辑:以下代码工作正常,但我更喜欢使用左+右锚点技术来指定宽度,而不是在宽度约束下。那不应该吗?

self.wtfView.translatesAutoresizingMaskIntoConstraints = false
self.wtfView.backgroundColor = UIColor.orange
self.wtfView.topAnchor.constraint(equalTo: self.passwordField.bottomAnchor, constant: 40.0).isActive = true
self.wtfView.leftAnchor.constraint(equalTo: self.containerView.leftAnchor, constant: 40.0).isActive = true
self.wtfView.widthAnchor.constraint(equalTo: self.containerView.widthAnchor, constant: -80.0).isActive = true //THE DIFFERENT ONE
self.wtfView.heightAnchor.constraint(equalToConstant: 50.0).isActive = true
self.wtfView.bottomAnchor.constraint(equalTo: self.containerView.bottomAnchor, constant: 040.0).isActive = true
Run Code Online (Sandbox Code Playgroud)

ori*_*ion 5

这样做的原因是 UIScrollView 的 contentView 仍然不知道您希望它占用其 parentView 的宽度。

您可以通过在 iOS11 中添加以下约束来解决此问题:

self.containerView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
Run Code Online (Sandbox Code Playgroud)

这表示“嘿,我希望您将内容宽度锁定到超级视图的宽度。

在 iOS 11 之前,您可以简单地将子视图约束到父视图的左右锚点和内容视图的左右锚点。

像这样:

self.wtfView.leftAnchor.constraint(equalTo: self.view.leftAnchor, constant: 40.0).isActive = true
self.wtfView.rightAnchor.constraint(equalTo: self.view.rightAnchor, constant: 40.0).isActive = true
Run Code Online (Sandbox Code Playgroud)

很像,Aleksei 的建议您现在将宽度限制为一个刚性值(父视图的宽度),并且滚动视图将使用它来决定滚动视图的宽度。