我怎么能让一个UIScrollView滚动到我的代码底部?或者用更一般的方式,到子视图的任意点?
当前回答
如果contentSize低于边界怎么办?
对于Swift来说,它是:
scrollView.setContentOffset(CGPointMake(0, max(scrollView.contentSize.height - scrollView.bounds.size.height, 0) ), animated: true)
其他回答
看起来这里所有的答案都没有考虑到安全区域。 从iOS 11开始,iPhone X引入了安全区域。这可能会影响scrollView的contentInset。
对于iOS 11及以上版本,正确地滚动到底部,包括插入的内容。你应该使用adjustedContentInset而不是contentInset。检查这段代码:
迅速:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
objective - c
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.adjustedContentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
Swift扩展(这保留了原来的contenttoffset .x):
extension UIScrollView {
func scrollsToBottom(animated: Bool) {
let bottomOffset = CGPoint(x: contentOffset.x,
y: contentSize.height - bounds.height + adjustedContentInset.bottom)
setContentOffset(bottomOffset, animated: animated)
}
}
引用:
adjustedContentInset
使用(可选)footerView和contentInset,解决方案是:
CGPoint bottomOffset = CGPointMake(0, _tableView.contentSize.height - tableView.frame.size.height + _tableView.contentInset.bottom);
if (bottomOffset.y > 0) [_tableView setContentOffset: bottomOffset animated: 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];
}
Xamarin的。iOS版本的接受答案
var bottomOffset = new CGPoint (0,
scrollView.ContentSize.Height - scrollView.Frame.Size.Height
+ scrollView.ContentInset.Bottom);
scrollView.SetContentOffset (bottomOffset, false);
最简单的解决方案:
[scrollview scrollRectToVisible:CGRectMake(scrollview.contentSize.width - 1,scrollview.contentSize.height - 1, 1, 1) animated:YES];
推荐文章
- 自动调整掩码大小编程vs接口生成器/ xib / nib
- NSUserDefaults -如何判断一个键是否存在
- Xcode UI测试用例中的延迟/等待
- 如何在Swift中删除视图的所有子视图?
- 属性getter和setter
- 裁剪一个UIImage
- 为什么我需要在swift的下划线?
- 我如何得到一个Swift枚举的计数?
- 是否有一个原因,Swift数组赋值是不一致的(既不是引用也不是深度复制)?
- 在Swift字符串中查找字符索引
- 这个应用程序是否使用广告标识符(IDFA)?—AdMob 6.8.0
- 无效上下文0x0在iOS 7.0和系统降级
- iOS 7: UITableView显示在状态栏下
- 如何产生类似ios7模糊视图的效果?
- 在这个块中强烈地捕获self很可能导致保留循环