如何让UIScrollView始终可滚动?

31

我有一个UIScrollViewscrollview.contentSize设置为UIScrollView中所有子视图的高度。当contentSize的高度大于UIScrollView的高度时,在拖动视图时它可以完美滚动。当contentSize的高度小于UIScrollView的高度时,拖动视图时不会发生任何事情。

我认为这是标准行为,因为实际上没有可滚动的内容。但我希望UIScrollView仍然能够移动一点。

一个可能的解决方案是确保contentSize的高度永远不小于frame.height加上一个小间距(例如5像素):

CGSize scrollSize = self.frame.size;
int defaultHeight = self.frame.size.height + 5;
int contentHeight = self.webView.frame.origin.y + self.webView.frame.size.height;
scrollSize.height = MAX(defaultHeight, contentHeight);
[self.scrollView setContentSize:scrollSize];

有没有更少 hack 的方法来做这件事呢?


你只是想让它弹跳吗? - jrtc27
我假设你已经尝试手动设置scrollEnabledYES,是吗? - Sergey Kalinichenko
是的,我只想让它弹跳 - 是的,scrollEnabled=YES 没有起作用。 - dhrm
当你在其中放置内容时,它是否会弹跳? - jrtc27
2个回答

82

UIScrollView 有两个属性听起来符合您的需求:

@property(nonatomic) BOOL alwaysBounceVertical; // default NO. if YES and bounces is YES, even if content is smaller than bounds, allow drag vertically
@property(nonatomic) BOOL alwaysBounceHorizontal; // default NO. if YES and bounces is YES, even if content is smaller than bounds, allow drag horizontally

只需将其中一个或两个设置为YES,您就可以获得弹跳效果。

这也可以在IB中设置,方法是勾选“水平弹跳”和/或“垂直弹跳”框:

enter image description here


4
请注意,除了“水平弹跳”或“垂直弹跳”之外,单独的“反弹”复选框也必须被勾选。 - Christopher Swasey
@ChristopherSwasey 不是针对我的。 - user5306470

7

在 Swift 中:

scrollView.alwaysBounceVertical = true
scrollView.alwaysBounceHorizontal = true

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接