简体   繁体   English

UI滚动视图未按预期滚动

[英]UI Scroll View doesn't scroll as intended

Using the storyboard and auto-layout I drag a scroll view into the view controller and satisfy auto-layout constraints appropriately. 使用情节提要和自动布局,我将滚动视图拖动到视图控制器中,并适当地满足自动布局约束。 I add in a Label centred on the screen with the appropriate auto-layout constraints. 我添加了一个标签,该标签以适当的自动布局约束在屏幕上居中。

Implemented the following code in viewDidLoad, viewWillAppear and viewDidLayoutSubviews (at different run times of course) 在viewDidLoad,viewWillAppear和viewDidLayoutSubviews中实现了以下代码(当然在不同的运行时间)

scrollView.contentSize.height = 1000

When running in the simulator the view only scrolls horizontally not vertically. 在模拟器中运行时,视图仅水平滚动而不垂直滚动。 It didn't make sense at first when seeing it scroll horizontally without applying specific conditions to do so, until i looked closely into the constraints. 一开始看到它在没有应用特定条件的情况下水平滚动时,这是没有意义的,直到我仔细查看了约束。

When initially dragging in a UIScrollView and selecting the Pin option to add constraints it shows the leading and trailing space to have a default value of -20 instead of 0. This seems to explain the automatic horizontal scrolling but still does not explain why I am not able to implement vertical scrolling. 最初在UIScrollView中拖动并选择Pin选项以添加约束时,它会显示前导和尾随空格的默认值为-20而不是0。这似乎在解释自动水平滚动,但仍不能解释为什么我不能够实现垂直滚动。

I have also tried specifying the content size using CGSize: 我也尝试过使用CGSize指定内容大小:

scrollView.contentSize = CGSize(400, 1000)

or 要么

scrollView.contentSize = CGSize(view.frame.width, 1000)

neither seem to work. 似乎都不起作用。 I also implemented the above methods with the same parameters using the initialiser CGSizeMake(width, height) and also does not work. 我还使用初始化程序CGSizeMake(width,height)用相同的参数实现了上述方法,并且也不起作用。

Scrolling is checked as enabled as are other options as per default when selecting a scroll view. 选择滚动视图时,默认情况下会检查滚动是否已启用以及其他选项。

You can set the constraints to centered horizontally and vertically in container view. 您可以将约束设置为在容器视图中水平居中和垂直居中。 This has the unfortunate effect of raising an error "Scroll view has ambiguous content size." 这具有引发错误“滚动视图的内容大小不明确”的不幸效果。 If you know for a fact you're going to set the content size in code, you can ignore it. 如果您知道要在代码中设置内容大小,则可以忽略它。

But it's probably a better practice to drag out an empty UIView call it containerView, pin it top/bottom/left/right to the scroll view center the label like above. 但是,最好拖出一个空的UIView称为containerView,将其顶部/底部/左侧/右侧固定到滚动视图的中心,使其像上面的标签一样,是一种更好的做法。 Set a constraint for the containerView's height. 设置containerView的高度的约束。 Then create an IBOutlet for the height constraint of the containerView call it containerViewHeightConstraint. 然后为containerView的高度约束创建一个IBOutlet,将其称为containerViewHeightConstraint。 Then in code say: 然后在代码中说:

self.containerViewHeightConstraint.constant = 1000 //or whatever height you want for scrolling 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM