Skip to content

Instantly share code, notes, and snippets.

@christopher-fuller
Last active February 22, 2018 09:19
Show Gist options
  • Save christopher-fuller/3aa72f4676c2e7efee833eb59c45803f to your computer and use it in GitHub Desktop.
Save christopher-fuller/3aa72f4676c2e7efee833eb59c45803f to your computer and use it in GitHub Desktop.
Paged scrolling for UITableView and UICollectionView
//
// PagingController.swift
// Paged scrolling for UITableView and UICollectionView
// Created by Christopher Fuller
//
// MIT License
//
// Copyright © 2018 Christopher Fuller
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import UIKit
typealias TableViewPagingController = PagingController.TableView
typealias CollectionViewPagingController = PagingController.CollectionView
class PagingController {
enum Error: Swift.Error {
case invalidConfiguration
}
private(set) var unrestricted: Bool
private(set) var startingContentOffset: CGPoint = .zero
private init(unrestricted: Bool) {
self.unrestricted = unrestricted
}
private func restrict(_ value: CGFloat, within delta: CGFloat, of target: CGFloat) -> CGFloat {
return min(max(value, target - delta), target + delta)
}
class TableView: PagingController {
public override init(unrestricted: Bool = false) {
super.init(unrestricted: unrestricted)
}
func draggingWillBegin(for tableView: UITableView) {
startingContentOffset = round(tableView.contentOffset, for: tableView)
}
@discardableResult
func draggingWillEnd(with targetContentOffset: UnsafeMutablePointer<CGPoint>,
for tableView: UITableView) throws -> Int {
let height = try rowHeight(for: tableView)
let contentOffset = round(targetContentOffset.pointee, for: tableView)
let y = unrestricted ? contentOffset.y : restrict(contentOffset.y,
within: height,
of: startingContentOffset.y)
targetContentOffset.pointee.y = y
return Int((y + tableView.contentInset.top + (height / 2)) / height)
}
private func round(_ contentOffset: CGPoint, for tableView: UITableView) -> CGPoint {
guard let height = try? rowHeight(for: tableView) else {
return contentOffset
}
let inset = tableView.contentInset.top
let y = ((contentOffset.y + inset) / height).rounded() * height - inset
return CGPoint(x: contentOffset.x, y: y)
}
private func rowHeight(for tableView: UITableView) throws -> CGFloat {
guard
tableView.rowHeight != UITableViewAutomaticDimension,
tableView.estimatedRowHeight == 0 else {
throw Error.invalidConfiguration
}
return tableView.rowHeight
}
}
class CollectionView: PagingController {
public override init(unrestricted: Bool = false) {
super.init(unrestricted: unrestricted)
}
func draggingWillBegin(for collectionView: UICollectionView) {
startingContentOffset = round(collectionView.contentOffset, for: collectionView)
}
@discardableResult
func draggingWillEnd(with targetContentOffset: UnsafeMutablePointer<CGPoint>,
for collectionView: UICollectionView) throws -> Int {
let layout = try flowLayout(for: collectionView)
let contentOffset = round(targetContentOffset.pointee, for: collectionView)
switch layout.scrollDirection {
case .horizontal:
let width = layout.itemSize.width
let x = unrestricted ? contentOffset.x : restrict(contentOffset.x,
within: width,
of: startingContentOffset.x)
targetContentOffset.pointee.x = x
return Int((x + collectionView.contentInset.left + (width / 2)) / width)
case .vertical:
let height = layout.itemSize.height
let y = unrestricted ? contentOffset.y : restrict(contentOffset.y,
within: height,
of: startingContentOffset.y)
targetContentOffset.pointee.y = y
return Int((y + collectionView.contentInset.top + (height / 2)) / height)
}
}
private func round(_ contentOffset: CGPoint, for collectionView: UICollectionView) -> CGPoint {
guard let layout = try? flowLayout(for: collectionView) else {
return contentOffset
}
switch layout.scrollDirection {
case .horizontal:
let inset = collectionView.contentInset.left
let width = layout.itemSize.width
let x = ((contentOffset.x + inset) / width).rounded() * width - inset
return CGPoint(x: x, y: contentOffset.y)
case .vertical:
let inset = collectionView.contentInset.top
let height = layout.itemSize.height
let y = ((contentOffset.y + inset) / height).rounded() * height - inset
return CGPoint(x: contentOffset.x, y: y)
}
}
private func flowLayout(for collectionView: UICollectionView) throws -> UICollectionViewFlowLayout {
guard
let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout,
layout.estimatedItemSize == .zero,
layout.sectionInset == .zero,
layout.minimumInteritemSpacing == 0,
layout.minimumLineSpacing == 0 else {
throw Error.invalidConfiguration
}
switch layout.scrollDirection {
case .horizontal:
let inset = collectionView.contentInset.top + collectionView.contentInset.bottom
guard layout.itemSize.height == collectionView.bounds.height - inset else {
throw Error.invalidConfiguration
}
case .vertical:
let inset = collectionView.contentInset.left + collectionView.contentInset.right
guard layout.itemSize.width == collectionView.bounds.width - inset else {
throw Error.invalidConfiguration
}
}
return layout
}
}
}
@christopher-fuller
Copy link
Author

Notes

  • Set scrollView.decelerationRate = UIScrollViewDecelerationRateFast for optimum paged scrolling experience
  • Must use fixed sizing (not estimated)
  • For UICollectionView specifically:
    • Either a single row or single column UICollectionViewFlowLayout must be utilized
    • sectionInset must be set to .zero
    • minimumInteritemSpacing and minimumLineSpacing must both be set to 0

@christopher-fuller
Copy link
Author

Example Usage

class ScrollViewDelegate: NSObject, UIScrollViewDelegate {

    private let pager: TableViewPagingController = .init()

    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        guard let tableView = scrollView as? UITableView else { return }
        pager.draggingWillBegin(for: tableView)
    }

    func scrollViewWillEndDragging(_ scrollView: UIScrollView,
                                   withVelocity velocity: CGPoint,
                                   targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        guard let tableView = scrollView as? UITableView else { return }
        do {
            let pageIndex = try pager.draggingWillEnd(with: targetContentOffset, for: tableView)
            print(pageIndex)
        } catch {}
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment