【问题标题】:UIScrollView Subviews not expanding to fill width (Autolayout)UIScrollView 子视图未扩展到填充宽度(自动布局)
【发布时间】:2018-03-08 08:00:51
【问题描述】:

我正在使用以下代码将视图约束到父 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

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

【问题讨论】:

    标签: ios cocoa-touch autolayout


    【解决方案1】:

    原因是UIScrollView的contentView还不知道你想让它占用它的parentView的宽度。

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

    self.containerView.contentLayoutGuide.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
    

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

    在 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
    

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

    【讨论】:

      【解决方案2】:

      可以尝试提供:

      self.wtfView.widthAnchor.constraint(equalTo: self.containerView.widthAnchor, constant: -40.0).isActive = true
      

      【讨论】:

      • 稍后我会试一试,但宽度约束不应该与左右锚点发生冲突吗?
      • 所以,这对我有用。如果我将左约束保持在 40,并添加一个带有 -80 的宽度约束,它看起来是正确的,但不应该提供一个左右锚就足够了吗?
      • 我也是这么想的,但是调试了很久发现需要提供宽度
      猜你喜欢
      • 1970-01-01
      • 2015-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多