2

I am looking for a way in Xcode and Swift to detect if my user has scrolled down the app.

If they have I would like to turn the view at the top of the app from transparent to black. If the user scrolls back to the top again, the view changes from black back to transparent.

Is this something which is achievable in Swift and Xcode?

Thanks in advance! :)

UPDATE Sorry I forgot to mention, I am using uiwebview, with my view overlaying above it. At the top of the app it will be transparent and when I scroll down the webview it will change to black. Can I still detect the scroll the same way?

Levi S
  • 45
  • 1
  • 10
  • check this post http://stackoverflow.com/questions/40667985/how-to-hide-the-navigation-bar-and-toolbar-as-scroll-down-swift-like-mybridge/40670196#40670196 – Joe Apr 03 '17 at 16:57

3 Answers3

4

Yes it is possible in swift. You have to use UIScrollViewDelegate methods to control the scrolling.

 func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {

    print("scrollViewWillBeginDecelerating")

    let actualPosition = scrollView.panGestureRecognizer.translation(in: scrollView.superview)
    if (actualPosition.y > 0){
        // Dragging down

        UIView.animate(withDuration: 3, animations: { 
           //Change the color of view
        })
    }else{
        // Dragging up

        UIView.animate(withDuration: 3, animations: {
            //Change the color of view
        })
    }
}
Rajeev Singh
  • 198
  • 1
  • 11
2

You can catch the scroll event by having your controller or some other class listen to the UISCrollViewDelegate protocol.

Particularly, look for scrollViewDidScroll (when scrolling starts) and scrollViewDidEndDecelerating (when scrolling ends).

The latter needs some time, so you could also check the contentOffset in scrollViewDidScroll to catch this condition instantly.

If you do not know how to change the backgroundColor of a view, ask another question.

Mundi
  • 79,884
  • 17
  • 117
  • 140
0

You have to implement scrollView method for detecting scrolling direction like bellow:

private var lastContentOffset: CGFloat = 0

    func scrollViewDidScroll(scrollView: UIScrollView!) {
        if (self.lastContentOffset > scrollView.contentOffset.y) {
            // move up
        }
        else if (self.lastContentOffset < scrollView.contentOffset.y) { 
           // move down
        }

        // update the new position 
        self.lastContentOffset = scrollView.contentOffset.y
    } 

reference : How to get UIScrollView vertical direction in Swift?

Community
  • 1
  • 1
Aashish1aug
  • 795
  • 1
  • 8
  • 22