很多问题都与此有关,但我对约束非常不满意。所以我添加了一个 UIScrollView
并且我想显示的 UIView
的高度为 700
并且这是固定的 700 没有动态高度。我对 UIScrollView
的约束是:
UIView
的约束是:
但它没有滚动。
最佳答案
当我需要一个可滚动的 View 时,我所做的如下 - 只需在 Storyboard 中检查你的约束并在那里做同样的事情(特别注意第二步):
我将
scrollView
添加到层次结构中并使用自动布局对其进行适当布局,例如,如果它应该覆盖的整个
:view
> View ControllerscrollView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ scrollView.leftAnchor.constraint(equalTo: self.view.leftAnchor), scrollView.rightAnchor.constraint(equalTo: self.view.rightAnchor), scrollView.topAnchor.constraint(equalTo: self.view.topAnchor), scrollView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor), ])
然后你需要在
scrollView
中添加一个contentView
并为其提供适当的布局约束,所以如果你想要垂直滚动scrollView
在我上面开始的示例中,您需要遵循自动布局约束:contentView.translatesAutoresizingMaskIntoConstraints = false NSLayoutConstraint.activate([ // horizontal anchors of contentView are constrained to scrollView superview // to prevent it from scrolling horizontally contentView.leftAnchor.constraint(equalTo: self.view.leftAnchor), contentView.rightAnchor.constraint(equalTo: self.view.rightAnchor), // but vertical anchors of contentView are constrained to // scrollView to allow scrolling contentView.topAnchor.constraint(equalTo: scrollView.topAnchor), contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), ])
请注意,我将
contentView
的leftAnchor
和rightAnchor
约束到self.view
而不是到scrollView
使其具有固定宽度。但是,顶部和底部 anchor 被限制在 ScrollView 中,因此当contentView
需要更多空间时,它们会展开并可滚动。现在您向
contentView
添加您想要的所有内容,并使用自动布局对其进行布局,就像contentView
是一个具有无限高度的 View 一样.或者您可以根据需要将其高度显式设置为 700。
关于ios - 在 UIScrollView 中滚动一个 UIView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48321859/