我的UIScrollView中有几个屏幕的内容,只能垂直滚动.
我想通过编程滚动到它的层次 struct 中包含的某个视图.
UIScrollView将移动,以便子视图位于UIScrollView的顶部(动画或非动画)
我的UIScrollView中有几个屏幕的内容,只能垂直滚动.
我想通过编程滚动到它的层次 struct 中包含的某个视图.
UIScrollView将移动,以便子视图位于UIScrollView的顶部(动画或非动画)
这是我最后写的一个扩展.
Usage:
从我的视图控制器self调用.scrollView是UIScrollView和self的一个出口.commentsHeader是其中的一个视图,靠近底部:
self.scrollView.scrollToView(self.commentsHeader, animated: true)
Code:
您只需要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)
}
}
}