以编程方式将滚动视图滚动到其底部

mrs*_*sim 1 xcode ios swift

我有一个滚动视图,我试图以编程方式滚动到它的底部..

试过这些:

extension UIScrollView {

// 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)

从:

在 Swift 中以编程方式将 UIScrollView 滚动到子 UIView(子视图)的顶部

  let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.size.height)
  scrollView.setContentOffset(bottomOffset, animated: true)
Run Code Online (Sandbox Code Playgroud)

从:

UIScrollView 以编程方式滚动到底部

但两者都没有做任何事情......

怎么做?

Usm*_*sar 5

这是滚动到滚动视图的任何特定子级、滚动视图顶部或滚动视图底部的代码。

只需将扩展代码添加到您的公共类并从您需要的地方调用它。

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)