我怎么能让一个UIScrollView滚动到我的代码底部?或者用更一般的方式,到子视图的任意点?
当前回答
只是对已有答案的一个改进。
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.contentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
它还负责底部的嵌入(以防你在键盘可见时使用它来调整滚动视图)
其他回答
如果你不需要动画,这是可行的:
[self.scrollView setContentOffset:CGPointMake(0, CGFLOAT_MAX) animated:NO];
用于水平ScrollView
如果你像我一样有一个水平ScrollView,想要滚动到它的结尾(在我的情况下,它的最右边),你需要改变接受的答案的某些部分:
objective - c
CGPoint rightOffset = CGPointMake(self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, 0 );
[self.scrollView setContentOffset:rightOffset animated:YES];
斯威夫特
let rightOffset: CGPoint = CGPoint(x: self.scrollView.contentSize.width - self.scrollView.bounds.size.width + self.scrollView.contentInset.right, y: 0)
self.scrollView.setContentOffset(rightOffset, animated: true)
类别来拯救!
将此添加到共享实用程序头的某处:
@interface UIScrollView (ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated;
@end
然后是那个实用程序实现:
@implementation UIScrollView(ScrollToBottom)
- (void)scrollToBottomAnimated:(BOOL)animated
{
CGPoint bottomOffset = CGPointMake(0, self.contentSize.height - self.bounds.size.height);
[self setContentOffset:bottomOffset animated:animated];
}
@end
然后在任何你喜欢的地方执行它,例如:
[[myWebView scrollView] scrollToBottomAnimated:YES];
将内容偏移设置为内容大小的高度是错误的:它将内容的底部滚动到滚动视图的顶部,因此看不到。
正确的解决方案是滚动内容的底部到滚动视图的底部,就像这样(sv是UIScrollView):
CGSize csz = sv.contentSize;
CGSize bsz = sv.bounds.size;
if (sv.contentOffset.y + bsz.height > csz.height) {
[sv setContentOffset:CGPointMake(sv.contentOffset.x,
csz.height - bsz.height)
animated:YES];
}
快速执行:
extension UIScrollView {
func scrollToBottom(animated: Bool) {
if self.contentSize.height < self.bounds.size.height { return }
let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
self.setContentOffset(bottomOffset, animated: animated)
}
}
使用它:
yourScrollview.scrollToBottom(animated: true)
推荐文章
- 如果模态ViewController演示样式为UIModalPresentationFormSheet, iPad键盘将不会解散
- 在UITableView中检测哪个UIButton被按下了
- 为iOS模拟器构建,但链接框架'****.framework'是为iOS构建的
- iOS更新后保留旧的启动屏幕和应用程序图标
- 如何象征崩溃日志Xcode?
- 以编程方式更改导航标题
- 我如何得到一个plist作为一个字典在Swift?
- Xcode - ld:没有为- lpods找到库
- 自动调整掩码大小编程vs接口生成器/ xib / nib
- NSUserDefaults -如何判断一个键是否存在
- Xcode UI测试用例中的延迟/等待
- 如何在Swift中删除视图的所有子视图?
- 属性getter和setter
- 裁剪一个UIImage
- 为什么我需要在swift的下划线?