scrolling a scrollview to its bottom programmatically

…衆ロ難τιáo~ 提交于 2020-12-06 16:08:15

问题


i have a scrollview and am trying to scroll to its bottom programmatically..

tried these:

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

}

from:

Programmatically scroll a UIScrollView to the top of a child UIView (subview) in Swift

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

from:

UIScrollView scroll to bottom programmatically

but both didn't do anything ...

how to do it?


回答1:


The offset setting doesn't works because you tried in calling early in the life cycle.

You could try updating the contentOffset at viewDidLayoutSubviews or viewDidAppear

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



回答2:


Here is the code to scroll to any specific child of scrollview, top of the scrollview or bottom of the scrollview..

simply add extension code to you common class and call it from where you need it.

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

}



回答3:


Use this piece of code for UIScrollView to scroll or start from the bottom:

let point = CGPoint(x: 0, y: self.view.frame.size.height) 
scrollView.contentOffset = point


来源:https://stackoverflow.com/questions/50832747/scrolling-a-scrollview-to-its-bottom-programmatically

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!