386 lines
17 KiB
Swift
386 lines
17 KiB
Swift
//
|
|
// Carousel.swift
|
|
// MVMCoreUI
|
|
//
|
|
// Created by Scott Pfeil on 7/2/19.
|
|
// Copyright © 2019 Verizon Wireless. All rights reserved.
|
|
//
|
|
|
|
import UIKit
|
|
|
|
open class Carousel: View {
|
|
|
|
public let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
|
|
|
|
/// The current index of the collection view. Includes dummy cells when looping.
|
|
public var currentIndex = 0
|
|
|
|
/// The index of the page, does not include dummy cells.
|
|
public var pageIndex: Int {
|
|
get {
|
|
return loop ? currentIndex - 2 : currentIndex
|
|
}
|
|
set(newIndex) {
|
|
currentIndex = loop ? newIndex + 2 : newIndex
|
|
}
|
|
}
|
|
|
|
/// The number of pages that there are. Used for the page control and for calculations. Should not include the looping dummy cells. Be sure to set this if subclassing and not using the molecules.
|
|
open var numberOfPages = 0
|
|
|
|
/// The json for the molecules.
|
|
var molecules: [MoleculeModelProtocol]?
|
|
|
|
/// The horizontal alignment of the cell in the collection view. Only noticeable if the itemWidthPercent is less than 100%.
|
|
var itemAlignment = UICollectionView.ScrollPosition.left
|
|
|
|
/// From 0-1. The item width as a percent of the carousel width.
|
|
public var itemWidthPercent: Float = 1
|
|
|
|
/// The height of the carousel. Default is 300.
|
|
public var collectionViewHeight: NSLayoutConstraint?
|
|
|
|
/// The view that we use for paging
|
|
public var pagingView: (UIView & MVMCoreUIPagingProtocol)?
|
|
|
|
/// If the carousel should loop after scrolling past the first and final cells.
|
|
var loop = false
|
|
private var dragging = false
|
|
|
|
// For adding pager
|
|
public var bottomPin: NSLayoutConstraint?
|
|
|
|
// MARK: - MVMCoreViewProtocol
|
|
open override func setupView() {
|
|
super.setupView()
|
|
guard collectionView.superview == nil else {
|
|
return
|
|
}
|
|
collectionView.translatesAutoresizingMaskIntoConstraints = false
|
|
collectionView.dataSource = self
|
|
collectionView.delegate = self
|
|
collectionView.showsHorizontalScrollIndicator = false
|
|
collectionView.backgroundColor = .clear
|
|
collectionView.isAccessibilityElement = false
|
|
addSubview(collectionView)
|
|
bottomPin = NSLayoutConstraint.constraintPinSubview(toSuperview: collectionView)?[ConstraintBot] as? NSLayoutConstraint
|
|
|
|
collectionViewHeight = collectionView.heightAnchor.constraint(equalToConstant: 300)
|
|
collectionViewHeight?.isActive = false
|
|
}
|
|
|
|
open override func updateView(_ size: CGFloat) {
|
|
super.updateView(size)
|
|
collectionView.collectionViewLayout.invalidateLayout()
|
|
showPeaking(false)
|
|
|
|
// Go to current cell. layoutIfNeeded is needed otherwise cellForItem returns nil for peaking logic. The dispatch is a sad way to ensure the collection view is ready to be scrolled.
|
|
DispatchQueue.main.async {
|
|
self.collectionView.scrollToItem(at: IndexPath(row: self.currentIndex, section: 0), at: self.itemAlignment, animated: false)
|
|
self.collectionView.layoutIfNeeded()
|
|
self.showPeaking(true)
|
|
}
|
|
}
|
|
|
|
// MARK: - MVMCoreUIMoleculeViewProtocol
|
|
public override func set(with model: MoleculeModelProtocol, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
|
|
super.set(with: model, delegateObject, additionalData)
|
|
guard let carouselModel = model as? CarouselModel else { return }
|
|
collectionView.backgroundColor = backgroundColor
|
|
collectionView.layer.borderColor = backgroundColor?.cgColor
|
|
collectionView.layer.borderWidth = (carouselModel.border ?? false) ? 1 : 0
|
|
backgroundColor = .white
|
|
|
|
registerCells(with: carouselModel, delegateObject: delegateObject)
|
|
setupLayout(with: carouselModel)
|
|
prepareMolecules(with: carouselModel)
|
|
itemWidthPercent = (carouselModel.itemWidthPercent ?? 100) / 100
|
|
setAlignment(with: carouselModel.itemAlignment)
|
|
|
|
if let height = carouselModel.height {
|
|
collectionViewHeight?.constant = CGFloat(height)
|
|
collectionViewHeight?.isActive = true
|
|
}
|
|
|
|
setupPagingMolecule(carouselModel.pagingMolecule, delegateObject: delegateObject)
|
|
collectionView.reloadData()
|
|
}
|
|
|
|
// MARK: - JSON Setters
|
|
/// Updates the layout being used
|
|
|
|
func setupLayout(with carouselModel: CarouselModel?) {
|
|
let layout = UICollectionViewFlowLayout()
|
|
layout.scrollDirection = .horizontal
|
|
layout.minimumLineSpacing = CGFloat(carouselModel?.spacing ?? 1)
|
|
layout.minimumInteritemSpacing = 0
|
|
collectionView.collectionViewLayout = layout
|
|
}
|
|
|
|
func prepareMolecules(with carouselModel: CarouselModel?) {
|
|
guard let newMolecules = carouselModel?.molecules else {
|
|
numberOfPages = 0
|
|
molecules = nil
|
|
return
|
|
}
|
|
|
|
numberOfPages = newMolecules.count
|
|
molecules = newMolecules
|
|
if carouselModel?.loop ?? false && newMolecules.count > 2 {
|
|
// Sets up the row data with buffer cells on each side (for illusion of endless scroll... also has one more buffer cell on each side in case we can peek that cell).
|
|
loop = true
|
|
molecules?.insert(newMolecules.last!, at: 0)
|
|
molecules?.insert(newMolecules[(newMolecules.count - 2)], at: 0)
|
|
molecules?.append(newMolecules.first!)
|
|
molecules?.append(newMolecules[1])
|
|
}
|
|
pageIndex = 0
|
|
}
|
|
|
|
/// Sets up the paging molecule
|
|
open func setupPagingMolecule(_ molecule: CarouselPagingModelProtocol?, delegateObject: MVMCoreUIDelegateObject?) {
|
|
var pagingView: (UIView & MVMCoreUIPagingProtocol)? = nil
|
|
if let molecule = molecule {
|
|
pagingView = MVMCoreUIMoleculeMappingObject.shared()?.createMolecule(molecule, delegateObject, false) as? (UIView & MVMCoreUIPagingProtocol)
|
|
}
|
|
addPaging(view: pagingView, position: (CGFloat(molecule?.position ?? 20)))
|
|
}
|
|
|
|
/// Registers the cells with the collection view
|
|
func registerCells(with carouselModel: CarouselModel, delegateObject: MVMCoreUIDelegateObject?) {
|
|
for molecule in carouselModel.molecules {
|
|
if let info = getMoleculeInfo(with: molecule, delegateObject: delegateObject) {
|
|
collectionView.register(info.class, forCellWithReuseIdentifier: info.identifier)
|
|
}
|
|
}
|
|
}
|
|
|
|
// MARK: - Convenience
|
|
/// Returns the (identifier, class) of the molecule for the given map.
|
|
func getMoleculeInfo(with molecule: MoleculeModelProtocol, delegateObject: MVMCoreUIDelegateObject?) -> (identifier: String, class: AnyClass, molecule: MoleculeModelProtocol)? {
|
|
guard let className = MVMCoreUIMoleculeMappingObject.shared()?.getMoleculeClass(molecule) else {
|
|
return nil
|
|
}
|
|
return ((className as? ModelMoleculeViewProtocol.Type)?.nameForReuse(with: molecule, delegateObject) ?? molecule.moleculeName, className, molecule)
|
|
}
|
|
|
|
/// Sets the alignment from the string.
|
|
open func setAlignment(with string: String?) {
|
|
switch string {
|
|
case "leading":
|
|
itemAlignment = .left
|
|
case "trailing":
|
|
itemAlignment = .right
|
|
case "center":
|
|
itemAlignment = .centeredHorizontally
|
|
default: break
|
|
}
|
|
}
|
|
|
|
/// Adds a paging view. Centers it horizontally with the collection view. The position is the vertical distance from the center of the page view to the bottom of the collection view.
|
|
open func addPaging(view: (UIView & MVMCoreUIPagingProtocol)?, position: CGFloat) {
|
|
pagingView?.removeFromSuperview()
|
|
guard let pagingView = view else {
|
|
bottomPin?.isActive = false
|
|
bottomPin = bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
|
|
bottomPin?.isActive = true
|
|
return
|
|
}
|
|
pagingView.translatesAutoresizingMaskIntoConstraints = false
|
|
addSubview(pagingView)
|
|
pagingView.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor).isActive = true
|
|
collectionView.bottomAnchor.constraint(equalTo: pagingView.centerYAnchor, constant: position).isActive = true
|
|
bottomAnchor.constraint(greaterThanOrEqualTo: pagingView.bottomAnchor).isActive = true
|
|
bottomPin?.isActive = false
|
|
bottomPin = bottomAnchor.constraint(equalTo: collectionView.bottomAnchor)
|
|
bottomPin?.priority = .defaultLow
|
|
bottomPin?.isActive = true
|
|
|
|
pagingView.setNumberOfPages(numberOfPages)
|
|
(pagingView as? MVMCoreUIViewConstrainingProtocol)?.alignHorizontal?(.fill)
|
|
pagingView.setPagingTouch { [weak self] (pager) in
|
|
MVMCoreDispatchUtility.performBlock(onMainThread: {
|
|
guard let localSelf = self else {
|
|
return
|
|
}
|
|
let currentPage = pager.currentPage()
|
|
localSelf.pageIndex = currentPage
|
|
localSelf.goTo(localSelf.currentIndex, animated: !UIAccessibility.isVoiceOverRunning)
|
|
})
|
|
}
|
|
self.pagingView = pagingView
|
|
}
|
|
|
|
open func showPeaking(_ peaking: Bool) {
|
|
if peaking && !UIAccessibility.isVoiceOverRunning {
|
|
// Show overlay and arrow in peaking Cell
|
|
let visibleItemsPaths = collectionView.indexPathsForVisibleItems.sorted { $0.row < $1.row }
|
|
if let firstItem = visibleItemsPaths.first, firstItem.row != currentIndex {
|
|
(collectionView.cellForItem(at: firstItem) as? MoleculeCollectionViewCell)?.setPeaking(true, animated: true)
|
|
}
|
|
if let lastItem = visibleItemsPaths.last, lastItem.row != currentIndex {
|
|
(collectionView.cellForItem(at: lastItem) as? MoleculeCollectionViewCell)?.setPeaking(true, animated: true)
|
|
}
|
|
} else {
|
|
// Hide peaking.
|
|
for item in collectionView.visibleCells {
|
|
(item as? MoleculeCollectionViewCell)?.setPeaking(false, animated: true)
|
|
}
|
|
}
|
|
}
|
|
|
|
public func setAccessiblity(_ cell: UICollectionViewCell?, index: Int) {
|
|
guard let cell = cell else {
|
|
return
|
|
}
|
|
if index == currentIndex {
|
|
cell.accessibilityElementsHidden = false
|
|
var array = cell.accessibilityElements
|
|
|
|
if let acc = pagingView?.accessibilityElements {
|
|
array?.append(contentsOf: acc)
|
|
} else {
|
|
array?.append(pagingView!)
|
|
}
|
|
|
|
self.accessibilityElements = array
|
|
} else {
|
|
cell.accessibilityElementsHidden = true
|
|
}
|
|
}
|
|
}
|
|
|
|
extension Carousel: UICollectionViewDelegateFlowLayout {
|
|
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
|
|
let itemWidth = collectionView.bounds.width * CGFloat(itemWidthPercent)
|
|
return CGSize(width: itemWidth, height: collectionView.bounds.height)
|
|
}
|
|
|
|
open func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
|
|
(cell as? MoleculeCollectionViewCell)?.setPeaking(false, animated: false)
|
|
}
|
|
}
|
|
|
|
extension Carousel: UICollectionViewDataSource {
|
|
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
|
|
return molecules?.count ?? 0
|
|
}
|
|
|
|
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
|
|
guard let molecule = molecules?[indexPath.row],
|
|
let moleculeInfo = getMoleculeInfo(with: molecule, delegateObject: nil) else {
|
|
return UICollectionViewCell()
|
|
}
|
|
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: moleculeInfo.identifier, for: indexPath)
|
|
if let protocolCell = cell as? MVMCoreUIMoleculeViewProtocol & ModelMoleculeViewProtocol {
|
|
protocolCell.reset?()
|
|
protocolCell.set(with: moleculeInfo.molecule, nil, nil)
|
|
protocolCell.updateView(collectionView.bounds.width)
|
|
}
|
|
setAccessiblity(cell, index: indexPath.row)
|
|
return cell
|
|
}
|
|
}
|
|
|
|
extension Carousel: UIScrollViewDelegate {
|
|
|
|
func goTo(_ index: Int, animated: Bool) {
|
|
showPeaking(false)
|
|
setAccessiblity(collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0)), index: index)
|
|
self.currentIndex = index
|
|
self.collectionView.scrollToItem(at: IndexPath(row: self.currentIndex, section: 0), at: self.itemAlignment, animated: animated)
|
|
if let cell = collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0)) {
|
|
setAccessiblity(collectionView.cellForItem(at: IndexPath(row: self.currentIndex, section: 0)), index: index)
|
|
UIAccessibility.post(notification: .layoutChanged, argument: cell)
|
|
}
|
|
}
|
|
|
|
func handleUserOnBufferCell() {
|
|
guard loop else {
|
|
return
|
|
}
|
|
|
|
let lastPageIndex = numberOfPages + 1
|
|
let goToIndex = {(index: Int) in
|
|
self.goTo(index, animated: false)
|
|
self.collectionView.layoutIfNeeded()
|
|
self.pagingView?.setPage(self.pageIndex)
|
|
}
|
|
|
|
if currentIndex < 2 {
|
|
// If on a "buffer" last row (which is the first index), go to the real last row secretly. layoutIfNeeded is needed otherwise cellForItem returns nil for peaking.
|
|
goToIndex(lastPageIndex)
|
|
} else if currentIndex > lastPageIndex {
|
|
// If on the "buffer" first row (which is the index after the real last row), go to the real first row secretly.
|
|
goToIndex(2)
|
|
}
|
|
}
|
|
|
|
func checkForDraggingOutOfBounds(_ scrollView: UIScrollView) {
|
|
guard loop, dragging else {
|
|
return
|
|
}
|
|
// Checks if the user is not paging but attempting to drag endlessly and goes out of bounds. Caps the index.
|
|
if let separatorWidth = (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing {
|
|
let itemWidth = collectionView.bounds.width * CGFloat(itemWidthPercent)
|
|
let index = scrollView.contentOffset.x / (itemWidth + separatorWidth)
|
|
let lastCellIndex = collectionView(collectionView, numberOfItemsInSection: 0) - 1
|
|
if index < 1 {
|
|
self.currentIndex = 0
|
|
} else if index > CGFloat(lastCellIndex - 1) {
|
|
self.currentIndex = lastCellIndex
|
|
}
|
|
}
|
|
|
|
handleUserOnBufferCell()
|
|
}
|
|
|
|
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
|
|
|
|
// Check if the user is dragging the card even further past the next card.
|
|
checkForDraggingOutOfBounds(scrollView)
|
|
|
|
// Let the pager know our progress if needed.
|
|
pagingView?.scrollViewDidScroll?(collectionView)
|
|
}
|
|
|
|
public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
|
|
dragging = true
|
|
showPeaking(false)
|
|
}
|
|
|
|
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
|
|
dragging = false
|
|
targetContentOffset.pointee = scrollView.contentOffset
|
|
|
|
// This is for setting up smooth custom paging. (Since UICollectionView only handles paging based on collection view size and not cell size).
|
|
guard let separatorWidth = (collectionView.collectionViewLayout as? UICollectionViewFlowLayout)?.minimumLineSpacing else {
|
|
return
|
|
}
|
|
|
|
// We switch cards if we pass the velocity threshold or position threshold (currently 50%).
|
|
let itemWidth = collectionView.bounds.width * CGFloat(itemWidthPercent)
|
|
var cellToSwipeTo = Int(scrollView.contentOffset.x/(itemWidth + separatorWidth) + 0.5)
|
|
let lastCellIndex = collectionView(collectionView, numberOfItemsInSection: 0) - 1
|
|
let velocityThreshold: CGFloat = 1.1
|
|
if velocity.x > velocityThreshold {
|
|
cellToSwipeTo = currentIndex + 1
|
|
} else if velocity.x < -velocityThreshold {
|
|
cellToSwipeTo = currentIndex - 1
|
|
}
|
|
|
|
// Cap the index.
|
|
goTo(min(max(cellToSwipeTo, 0), lastCellIndex), animated: true)
|
|
}
|
|
|
|
// To give the illusion of endless scrolling. Since we are always calling scrollToItem we can assume finished paging in here.
|
|
public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
|
|
// Cycle to other end if on buffer cell.
|
|
handleUserOnBufferCell()
|
|
|
|
pagingView?.setPage(pageIndex)
|
|
|
|
showPeaking(true)
|
|
}
|
|
}
|