在UIScrollView中滚动UIView [英] Scroll a UIView in UIScrollView
问题描述
与此相关的问题很多,但是约束非常糟糕.因此,我添加了 UIScrollView
和要显示的 UIView
高度为 700
,并且此高度固定为700,没有动态高度.我对 UIScrollView
的约束是:
A lot of questions are available with this but I'm very bad with constraints. So I've added a UIScrollView
and the UIView
I want to show has height of 700
and this is fixed 700 no dynamic height. The constraints I've for UIScrollView
are:
对于 UIView
,约束为:
但是它没有滚动.
推荐答案
需要滚动视图时,我要做的是-在情节提要中检查您的约束,然后在其中进行同样的操作(尤其要注意第二步):
What I do when I need a scrollable view is what follows - just go over your constraints in storyboards and do the same there (especially pay attention to second step):
-
我将
scrollView
添加到层次结构中,并使用自动布局正确地布局它,例如,如果它应该覆盖的整个
:view
> viewController
I add a
scrollView
to the hierarchy and use autolayout to properly layout it, e.g., if it is supposed to cover the wholeview
of theviewController
:
scrollView.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
在我上面开始的示例中,您需要遵循以下自动布局约束:
Then you need to add a contentView
to the scrollView
and provide a proper layout constraints for it, so if you want vertically scrollable scrollView
in the example I started above, you need following autolayout constraints:
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
使其具有固定宽度.但是,顶部和底部锚点限制在scrollView上,因此当 contentView
需要更多空间时,它们会展开并滚动.
Notice here that I constrained the leftAnchor
and rightAnchor
of the contentView
to the self.view
rather than to scrollView
to make it of fixed width. However, top and bottom anchors are constrained to the scrollView, so they are expanded and scrollable when contentView
needs more space.
现在,您将所需的所有内容添加到 contentView
中,并使用autolayout对其进行布局,就像 contentView
是一个无限高的视图一样.或者,您可以根据需要将其高度明确设置为700.
Now you add to the contentView
all the content that you want, and you lay it out using autolayout as if the contentView
was a view with infinite height. Or you can just explicitly set its height to 700 as you want.
这篇关于在UIScrollView中滚动UIView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!