Paginated UIScrollView, a UIPageViewController replacement that supports UIViews instead of UIViewControllers.
import UIKit
class RootController: UIViewController {
var pages: [UIView] = []
lazy var scrollView: PaginatedScrollView = {
let view = PaginatedScrollView(dataSource: self)
view.delegate = self
return view
}()
override func viewDidLoad() {
super.viewDidLoad()
setupPages()
view.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
scrollView.topAnchor.constraint(equalTo: view.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
private func setupPages() {
let firstPage = UIView()
firstPage.backgroundColor = .red
pages.append(firstPage)
let secondPage = UIView()
secondPage.backgroundColor = .green
pages.append(secondPage)
let thirdPage = UIView()
thirdPage.backgroundColor = .blue
pages.append(thirdPage)
}
}
extension RootController: PaginatedScrollViewDataSource {
func numberOfPagesInPaginatedScrollView(_ paginatedScrollView: PaginatedScrollView) -> Int {
return pages.count
}
func paginatedScrollView(_ paginatedScrollView: PaginatedScrollView, viewAtIndex index: Int) -> UIView {
return pages[index]
}
}
extension RootController: PaginatedScrollViewDelegate {
func paginatedScrollView(_ paginatedScrollView: PaginatedScrollView, didMoveToIndex index: Int) {
print("Did move to page \(index)")
}
func paginatedScrollView(_ paginatedScrollView: PaginatedScrollView, willMoveFromIndex index: Int) {
print("Will move from page \(index)")
}
}
// Reloads all pages.
public func reloadData()
// Moves to the next page.
public func moveToNextPage()
// Moves to the previous page.
public func moveToPreviousPage()
UIPageViewController
is kind of lame when it comes to knowing exactly when you have switched to the next page or went back to the previous one. That's the main reason why PaginatedScrollView
exists.
public protocol PaginatedScrollViewDelegate: AnyObject {
func paginatedScrollView(_ paginatedScrollView: PaginatedScrollView, willMoveFromIndex index: Int)
func paginatedScrollView(_ paginatedScrollView: PaginatedScrollView, didMoveToIndex index: Int)
}
PaginatedScrollView
is available through Swift Package Manager.
PaginatedScrollView is available under the MIT license. See the LICENSE file for more info.
Elvis Nunez, @3lvis