我需要在 UIScrollView
中添加一个 containerView ,然后在containerView中添加多个 subview 。出于某种原因,containerView 不尊重 top/bottom/left/rightAnchor
约束,但它适用于 width/height/centerX/centerYAnchor
注意:如果 superview 是 UIView
而不是 UIScrollView
,它工作正常。
该项目100%基于代码。使用 Swift 4.1 和 Xcode 9.4
这不起作用
containerView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true
containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 0).isActive = true
containerView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0).isActive = true
这个作品
containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
containerView.centerXAnchor.constraint(equalTo: scrollView.centerXAnchor).isActive = true
containerView.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor).isActive = true
在这两种情况下,
scrollView.constraints
数组总共包括 4 个约束。有趣的是它们的打印输出是不同的。一些不起作用的约束(.
top
和 . left
)使用自动布局视觉格式语言打印。另外,请注意第三个中的 (LTR):ScrollView [
<NSLayoutConstraint:V:|-(0)-[UIView] (active, names: '|':UIScrollView:)>,
<NSLayoutConstraint:UIView.bottom == UIScrollView.bottom (active)>,
<NSLayoutConstraint:H:|-(0)-[UIView](LTR) (active, names: '|':UIScrollView:)>,
<NSLayoutConstraint:UIView.right == UIScrollView.right (active)>]
有效的约束打印如下:
ScrollView [
<NSLayoutConstraint:UIView.width == UIScrollView.width (active)>,
<NSLayoutConstraint:UIView.height == UIScrollView.height (active)>,
<NSLayoutConstraint:UIView.centerX == UIScrollView.centerX (active)>,
<NSLayoutConstraint:UIView.centerY == UIScrollView.centerY (active)>]
我研究了 StackOverflow,发现了几个问题,例如 this ,但他们并没有真正帮助我解释问题所在(或
UIScrollView
约束要求)。有任何想法吗?
最佳答案
UIScrollView 需要滚动其中的一些内容。您正在添加的 View (在 ScrollView 内)没有大小(高度和宽度),因此 ScrollView 无法识别其内容的大小。
为 View 添加大小(在 ScrollView 内),它将起作用。
containerView.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 0).isActive = true
containerView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: 0).isActive = true
containerView.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 0).isActive = true
containerView.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: 0).isActive = true
// Size constraints
containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor).isActive = true
containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor).isActive = true
// To check scrolling of container view; try this
containerView.widthAnchor.constraint(equalTo: scrollView.widthAnchor + 50.0).isActive = true
containerView.heightAnchor.constraint(equalTo: scrollView.heightAnchor + 50.0).isActive = true
关于ios - UIScrollView 中的 UIView 尊重一些约束,但不尊重其他约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51997286/