397 lines
17 KiB
Swift
397 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: ViewConstrainingView, ModelMoleculeViewProtocol {
|
|
|
|
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
|
|
|
|
/// The current index of the collection view. Includes dummy cells when looping.
|
|
var currentIndex = 0
|
|
|
|
/// The index of the page, does not include dummy cells.
|
|
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.
|
|
var numberOfPages = 0
|
|
|
|
/// The json for the molecules.
|
|
var molecules: [MoleculeProtocol]?
|
|
|
|
/// 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.
|
|
var itemWidthPercent: Float = 1
|
|
|
|
/// The height of the carousel. Default is 300.
|
|
var collectionViewHeight: NSLayoutConstraint?
|
|
|
|
/// The view that we use for paging
|
|
var pagingView: (UIView & MVMCoreUIPagingProtocol)?
|
|
|
|
/// If the carousel should loop after scrolling past the first and final cells.
|
|
var loop = false
|
|
private var dragging = false
|
|
|
|
// 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)
|
|
pinView(toSuperView: collectionView)
|
|
|
|
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
|
|
//TODO: Model, Change to model
|
|
public func setWithModel(_ model: MoleculeProtocol?, _ delegateObject: MVMCoreUIDelegateObject?, _ additionalData: [AnyHashable: Any]?) {
|
|
guard let caroselModel = model as? CarouselModel else {
|
|
return
|
|
}
|
|
|
|
#warning("This below call should be repaced with super.setWithModel once we get rid of ViewConstrainingView.")
|
|
//TODO: This below call should be repaced with super.setWithModel once we get rid of ViewConstrainingView.
|
|
setUpDefaultWithModel(model, delegateObject, additionalData)
|
|
|
|
collectionView.backgroundColor = backgroundColor
|
|
collectionView.layer.borderColor = backgroundColor?.cgColor
|
|
collectionView.layer.borderWidth = (caroselModel.border ?? false) ? 1 : 0
|
|
backgroundColor = .white
|
|
|
|
registerCells(with: caroselModel, delegateObject: delegateObject)
|
|
setupLayout(with: caroselModel)
|
|
prepareMolecules(with: caroselModel)
|
|
itemWidthPercent = (caroselModel.itemWidthPercent ?? 100) / 100
|
|
setAlignment(with: caroselModel.itemAlignment)
|
|
|
|
if let height = caroselModel.height {
|
|
collectionViewHeight?.constant = CGFloat(height)
|
|
collectionViewHeight?.isActive = true
|
|
}
|
|
|
|
setupPagingMolecule(caroselModel.pagingMolecule, delegateObject: delegateObject)
|
|
collectionView.reloadData()
|
|
}
|
|
|
|
|
|
open override func shouldSetHorizontalMargins(_ shouldSet: Bool) {
|
|
super.shouldSetHorizontalMargins(shouldSet)
|
|
updateViewHorizontalDefaults = false
|
|
}
|
|
|
|
// 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: PagingMoleculeProtocol?, 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: MoleculeProtocol, delegateObject: MVMCoreUIDelegateObject?) -> (identifier: String, class: AnyClass, molecule: MoleculeProtocol)? {
|
|
guard let className = MVMCoreUIMoleculeMappingObject.shared()?.getMoleculeClass(molecule) ,
|
|
let moleculeName = (className as? ModelMoleculeViewProtocol.Type)?.nameForReuse(molecule, delegateObject) ?? molecule.moleculeName else {
|
|
return nil
|
|
}
|
|
return (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)
|
|
}
|
|
}
|
|
}
|
|
|
|
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 {
|
|
public 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)
|
|
}
|
|
|
|
public func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
|
|
(cell as? MoleculeCollectionViewCell)?.setPeaking(false, animated: false)
|
|
}
|
|
}
|
|
|
|
extension Carousel: UICollectionViewDataSource {
|
|
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
|
|
return molecules?.count ?? 0
|
|
}
|
|
|
|
public 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.setWithModel(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()
|
|
}
|
|
|
|
public 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)
|
|
}
|
|
}
|