本文翻译自:UIScrollView scroll to bottom programmatically
How can I make a UIScrollView
scroll to the bottom within my code? 如何使UIScrollView
滚动到代码底部? Or in a more generic way, to any point of a subview? 还是以更通用的方式,到子视图的任何一点?
#1楼
参考:https://stackoom.com/question/3ZLu/UIScrollView以编程方式滚动到底部
#2楼
Category to the rescue! 分类抢救!
Add this to a shared utility header somewhere: 将此添加到共享公用程序标头中:
@interface UIScrollView (ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated;
@end
And then to that utility implementation: 然后执行该实用程序:
@implementation UIScrollView(ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated
{
CGPoint bottomOffset = CGPointMake(0, self.contentSize.height - self.bounds.size.height);
[self setContentOffset:bottomOffset animated:animated];
}
@end
Then Implement it wherever you like, for instance: 然后在任意位置实现它,例如:
[[myWebView scrollView] scrollToBottomAnimated:YES];
#3楼
A good way to ensure the bottom of your content is visible is to use the formula: 确保可见内容底部的一种好方法是使用以下公式:
contentOffsetY = MIN(0, contentHeight - boundsHeight)
This ensures the bottom edge of your content is always at or above the bottom edge of the view. 这样可以确保内容的底边始终位于视图底边或上方。 The MIN(0, ...)
is required because UITableView
(and probably UIScrollView
) ensures contentOffsetY >= 0
when the user tries to scroll by visibly snapping contentOffsetY = 0
. MIN(0, ...)
是必需的,因为当用户尝试通过明显捕捉contentOffsetY = 0
进行滚动时, UITableView
(可能还有UIScrollView
)确保contentOffsetY >= 0
contentOffsetY = 0
。 This looks pretty weird to the user. 对用户来说,这看起来很奇怪。
The code to implement this is: 实现此目的的代码是:
UIScrollView scrollView = ...;
CGSize contentSize = scrollView.contentSize;
CGSize boundsSize = scrollView.bounds.size;
if (contentSize.height > boundsSize.height)
{
CGPoint contentOffset = scrollView.contentOffset;
contentOffset.y = contentSize.height - boundsSize.height;
[scrollView setContentOffset:contentOffset animated:YES];
}
#4楼
Just an enhancement to the existing answer. 只是对现有答案的增强。
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.contentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
It takes care of the bottom inset as well (in case you're using that to adjust your scroll view when the keyboard is visible) 它还会照顾底部的插图(以防您在可见键盘时使用它来调整滚动视图)
#5楼
如果您不需要动画,可以使用以下方法:
[self.scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX) animated:NO];
#6楼
CGFloat yOffset = scrollView.contentOffset.y;
CGFloat height = scrollView.frame.size.height;
CGFloat contentHeight = scrollView.contentSize.height;
CGFloat distance = (contentHeight - height) - yOffset;
if(distance < 0)
{
return ;
}
CGPoint offset = scrollView.contentOffset;
offset.y += distance;
[scrollView setContentOffset:offset animated:YES];