swiftxcodeuiscrollviewcontentoffset

How to use the scroll view content offset property?


I have the following code:

   if scrollView.contentOffset.x == 10 {
            print("works")
        }

Although when I scroll to the left or right nothing get's printed to the console. I know this is really basic although I'm just trying to understand this before I dive deeper.


Solution

  • I put this in the view did load

    That means the code will check the content offset at the moment of loading the view. At that moment, if the scroll view has an x offset of exactly 10, the message will be printed. It doesn't care about what happens after that moment.

    It seems like you want it to print the message when you manually scrolled the scroll view to a certain offset.

    One way to do this is to move the code to scrollViewDidScroll. This function is called every time the content offset changes.

    extension YourViewController: UIScrollViewDelegate {
        func scrollViewDidScroll(_ scrollView: UIScrollView) {
            // this checks for whether contentOffset.x is around 10 (contented shifted to the right by 10 points)
            if abs(scrollView.contentOffset.x - 10) < 1 {
                print("works")
            }
        }
    }
    

    and remember to set the scroll view's delegate to self:

    scrollView.delegate = self
    

    Note that I changed the condition to abs(scrollView.contentOffset.x - 10) < 1. This is to give it some "allowance", rather than saying that the x offset has to be exactly 10. When you scroll, the content offset seldom changes to exactly 10 (or exactly anything, for that matter). You'd have to be an extremely accurate scroller to do that :) Therefore, I allow any value from 9 to 11 to pass the check. But even with this allowance, "works" won't be printed if you scroll fast. Because as you scroll faster, content offset changes by a larger amount each time. You might want to adjust the allowance to your needs.

    If you want to print "works" every time the user stops scrolling instead, you can implement the following two methods:

    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        if abs(scrollView.contentOffset.x - 10) < 1 {
            print("works")
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if abs(scrollView.contentOffset.x - 10) < 1 {
            print("works")
        }
    }