39
votes

Is there a way to deactivate the decelerating of a UIScrollView?

I want to allow the user to scroll the canvas, but I don't want that the canvas continues scrolling after the user lifted the finger.

5
Adam, I'm aware that changing the default behavior isn't recommend but I think in my special case it would make sense. I'm implementing an extended canvas with the ability to edit objects directly on the canvas. When entering this on-canvas-edit mode I would like to restrict the distance the user scrolls so that the object is alway in the visible range. The use is allowed to scroll further, but it would bounce back on finger up. I'm aware of the contentSize property, but it interferes with my growing canvas.Markus Müller-Simhofer
In my situation, we were doing paid for hire work and the client requested that we remove the deceleration motion.Mark

5 Answers

70
votes

This can be done by utilizing the UIScrollView delegate method scrollViewWillBeginDecelerating to automatically set the content offset to the current screen position.

To implement:

  1. Assign a delegate to your UIScrollView object if you have not already done so.
  2. In your delegate's .m implementation file, add the following lines of code:

    -(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{  
        [scrollView setContentOffset:scrollView.contentOffset animated:YES];   
    }
    

Voila! No more auto-scroll.

42
votes

For iOS 5.0 or later, there is a better method than calling setContentOffset:animated:.

Implement delegate method scrollViewWillEndDragging:withVelocity:targetContentOffset: in your .m file:

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
              targetContentOffset:(inout CGPoint *)targetContentOffset {
    targetContentOffset.pointee = scrollView.contentOffset;
}

Assigning the current offset to targetContentOffset stops the UIScrollView from auto-scrolling.

20
votes

You can just turn up the deceleration rate very high. With an infinite rate, it would stop immediately. Try setting the rate to these constants:

scrollView.decelerationRate = UIScrollViewDecelerationRateNormal;

and

scrollView.decelerationRate = UIScrollViewDecelerationRateFast;

If fast still isn't fast enough for you, UIScrollViewDecelerationRateFast is just typedef'ed as a float, so you can just multiply it by a factor of 10 or so to speed it up even more.

1
votes

Just set the decelerationRate property to 0

It will disable the auto scrolling property. But keep in mind the user interaction will become bad if scrollview contentsize is big.

0
votes

Previous Swift version:↓

scrollView.decelerationRate = UIScrollView.DecelerationRate.fast

Current Swift 4.2 version code:↓

scrollView.decelerationRate = UIScrollViewDecelerationRateFast