func setContentOffset(scrollView: UIScrollView) {
let numOfItems = itemCount // 5
let stopOver = scrollView.contentSize.width / CGFloat(numOfItems)
let x = round(scrollView.contentOffset.x / stopOver) * stopOver
guard x >= 0 && x <= scrollView.contentSize.width - scrollView.frame.width else {
return
}
scrollView.setContentOffset(CGPointMake(x, scrollView.contentOffset.y), animated: true)
}
extension ViewController: UIScrollViewDelegate {
func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
setContentOffset(scrollView)
}
func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
guard !decelerate else {
return
}
setContentOffset(scrollView)
}
}
Also made a demo project in Github
https://github.com/rishi420/ScrollViewCustomPaging
Update:
Trying to consider for the scrolling velocity when user endDragging.
var velocityX = CGFloat(0.0)
.
func setContentOffset(scrollView: UIScrollView) {
let numOfItems = itemCount
let stopOver = scrollView.contentSize.width / CGFloat(numOfItems)
var x = round((scrollView.contentOffset.x + (velocityX * 150)) / stopOver) * stopOver // 150 is for test. Change it for your liking
x = max(0, min(x, scrollView.contentSize.width - scrollView.frame.width))
scrollView.setContentOffset(CGPointMake(x, scrollView.contentOffset.y), animated: true)
}
.
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
{
velocityX = velocity.x
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…