1

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?

mrs.bassim
  • 469
  • 2
  • 7
  • 16

4 Answers4

8

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

}
Usman Nisar
  • 3,031
  • 33
  • 41
4

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)
Lal Krishna
  • 15,485
  • 6
  • 64
  • 84
0

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
shanezzar
  • 1,031
  • 13
  • 17
0

You add this code as extension to scrollView

  func scrollToBottom(animated: Bool = true) {
    let bottomOffset = CGPoint(x: 0, y: self.contentSize.height - self.bounds.size.height)
    self.setContentOffset(bottomOffset, animated: true)
}