Manually bounce UIScrollView

2.1k views Asked by At

With UIScrollView, it's possible to programmatically move to an offset, with setContentOffset:animated: for exemple.

I'm trying to add a bounce effect when the offset is set programmatically. I think I should use a UIAttachmentBehavior, but I don't really know how to use it.

When should it be declared ? When the user finish dragging, in the scrollViewDidEndDragging function ? Or when the offset is the same than the final offset ?

For exemple, I'm at offset 10 and I want to go to offset 50. Maybe I should go to offset 60 and set a UIAttachmentBehavior at offset 50 ? Or maybe there's an other way ?

Thanks for your help

1

There are 1 answers

0
Hayley Guillou On

From my understanding, you want to enable bouncing when you get to the edge of a scroll view.

If you want the default of the scrollview to be that it doesn't bounce, then use this code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.scrollview.bounces = false
}

Then, if you want to enable bouncing at any point, just add the line:

self.scrollview.bounces = true

If you know that you always want to scrollview to bounce you can set the following properties:

self.scrollview.alwaysBounceVertical = true
self.scrollview.alwaysBounceHorizontal = true

See this link for more information.