我怎么能让一个UIScrollView滚动到我的代码底部?或者用更一般的方式,到子视图的任意点?
当前回答
滚动到顶部
- CGPoint topOffset = CGPointMake(0, 0);
- [scrollView setContentOffset:topOffset animated:YES];
滚动到底部
- CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - self.scrollView.bounds.size.height);
- [scrollView setContentOffset:bottomOffset animated:YES];
其他回答
滚动到顶部
- CGPoint topOffset = CGPointMake(0, 0);
- [scrollView setContentOffset:topOffset animated:YES];
滚动到底部
- CGPoint bottomOffset = CGPointMake(0, scrollView.contentSize.height - self.scrollView.bounds.size.height);
- [scrollView setContentOffset:bottomOffset animated:YES];
我发现contentSize并没有真正反映文本的实际大小,所以当尝试滚动到底部时,它会有点偏离。确定实际内容大小的最佳方法实际上是使用NSLayoutManager的usedRectForTextContainer:方法:
UITextView *textView;
CGSize textSize = [textView.layoutManager usedRectForTextContainer:textView.textContainer].size;
要确定在UITextView中实际显示了多少文本,可以通过从帧高度中减去文本容器嵌入来计算。
UITextView *textView;
UIEdgeInsets textInsets = textView.textContainerInset;
CGFloat textViewHeight = textView.frame.size.height - textInsets.top - textInsets.bottom;
然后就很容易滚动了:
// if you want scroll animation, use contentOffset
UITextView *textView;
textView.contentOffset = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
// if you don't want scroll animation
CGRect scrollBounds = textView.bounds;
scrollBounds.origin = CGPointMake(textView.contentOffset.x, textSize - textViewHeight);
textView.bounds = scrollBounds;
一些数字用于参考空UITextView的不同大小。
textView.frame.size = (width=246, height=50)
textSize = (width=10, height=16.701999999999998)
textView.contentSize = (width=246, height=33)
textView.textContainerInset = (top=8, left=0, bottom=8, right=0)
Xamarin的。iOS版本的接受答案
var bottomOffset = new CGPoint (0,
scrollView.ContentSize.Height - scrollView.Frame.Size.Height
+ scrollView.ContentInset.Bottom);
scrollView.SetContentOffset (bottomOffset, false);
滚动到表的最后一项的解决方案
Swift 3:
if self.items.count > 0 {
self.tableView.scrollToRow(at: IndexPath.init(row: self.items.count - 1, section: 0), at: UITableViewScrollPosition.bottom, animated: true)
}
扩展UIScrollView添加一个scrollToBottom方法:
extension UIScrollView {
func scrollToBottom(animated:Bool) {
let offset = self.contentSize.height - self.visibleSize.height
if offset > self.contentOffset.y {
self.setContentOffset(CGPoint(x: 0, y: offset), animated: animated)
}
}
}
推荐文章
- 如果模态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的下划线?