dys*_*rns 30 uiscrollview ios swift
我的UIScrollView中有几个屏幕内容,只能垂直滚动.
我想以编程方式滚动到包含在其层次结构中的某个视图.
UIScrollView移动,以便子视图位于UIScrollView的顶部(动画或不动画)
dys*_*rns 81
这是我最后写的扩展.
用法:
从我的viewController调用,self.scrollView是UIScrollView的出口,self.commentsHeader是其中的一个视图,靠近底部:
self.scrollView.scrollToView(self.commentsHeader, animated: true)
Run Code Online (Sandbox Code Playgroud)
码:
您只需要scrollToView方法,但也可以使用scrollToBottom/scrollToTop方法,因为您可能也需要这些方法,但可以随意删除它们.
extension UIScrollView {
// Scroll to a specific view so that it's top is at the top our scrollview
func scrollToView(view:UIView, animated: Bool) {
if let origin = view.superview {
// Get the Y position of your child view
let childStartPoint = origin.convertPoint(view.frame.origin, toView: self)
// Scroll to a rectangle starting at the Y of your subview, with a height of the scrollview
self.scrollRectToVisible(CGRect(x:0, y:childStartPoint.y,width: 1,height: self.frame.height), animated: animated)
}
}
// Bonus: Scroll to top
func scrollToTop(animated: Bool) {
let topOffset = CGPoint(x: 0, y: -contentInset.top)
setContentOffset(topOffset, animated: animated)
}
// Bonus: Scroll to bottom
func scrollToBottom() {
let bottomOffset = CGPoint(x: 0, y: contentSize.height - bounds.size.height + contentInset.bottom)
if(bottomOffset.y > 0) {
setContentOffset(bottomOffset, animated: true)
}
}
}
Run Code Online (Sandbox Code Playgroud)
scrollView.scrollRectToVisible(CGRect(x: x, y: y, width: 1, height:
1), animated: true)
Run Code Online (Sandbox Code Playgroud)
要么
scrollView.setContentOffset(CGPoint(x: x, y: y), animated: true)
Run Code Online (Sandbox Code Playgroud)
另一种方式是
scrollView.contentOffset = CGPointMake(x,y);
Run Code Online (Sandbox Code Playgroud)
我用这样的动画做到了
[UIView animateWithDuration:2.0f delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
scrollView.contentOffset = CGPointMake(x, y); }
completion:NULL];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
29290 次 |
| 最近记录: |