iosswiftuiscrollviewuiscrollviewdelegate

How to change UIScrollView with isPagingEnabled autoscroll drag trashhold


I have horizontal UIScrollView with isPagingEnabled = true containing few pages. If I drag scrollview content and release finger it scrolls to next page only if I dragged at least 50% of scrollview width. I want to auto scroll to next/previous page if drag distance is more than 25%.

I was able to achieve it by overriding scrollViewDidEndDragging in UIScrollViewDelegate, calculating drag distance and calling scrollView.setContentOffset. But issue is that if distance > 25 and < 50 then it scrolls back automatically probably because scrollview calls it's default implementation.

Any idea how can I achieve this? Thanks


Solution

  • I would use the following delegate's callback by modifying offset to desired page

    // called on finger up if the user dragged. velocity is in points/millisecond. 
    // targetContentOffset may be changed to adjust where the scroll view comes to rest
    @available(iOS 5.0, *)
    optional func scrollViewWillEndDragging(_ scrollView: UIScrollView, 
        withVelocity velocity: CGPoint, 
        targetContentOffset: UnsafeMutablePointer<CGPoint>)