Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save beccadax/9a63fed72c84b3304b68ddbc0624f2d6 to your computer and use it in GitHub Desktop.
Save beccadax/9a63fed72c84b3304b68ddbc0624f2d6 to your computer and use it in GitHub Desktop.
Collection for iterating through index paths in a collection view. Could be generalized.
//
// UICollectionViewLayout+indexPaths.swift
// Converter Calc
//
// Created by Brent Royal-Gordon on 7/26/17.
// Copyright © 2017 Architechies. All rights reserved.
//
import UIKit
extension UICollectionViewLayout {
var indexPaths: IndexPathView {
return IndexPathView(collectionView: collectionView)
}
struct IndexPathView: BidirectionalCollection {
var collectionView: UICollectionView?
var numberOfSections: Int {
return collectionView?.numberOfSections ?? 0
}
func numberOfItems(inSection section: Int) -> Int {
return collectionView?.numberOfItems(inSection: section) ?? 0
}
var startIndex: IndexPath {
return [0, 0]
}
var endIndex: IndexPath {
return [numberOfSections, 0]
}
func index(before i: IndexPath) -> IndexPath {
if i.item > 0 {
return [i.section, i.item - 1]
}
precondition(i.section > 0, "Invalid index path")
let newSection = i.section - 1
let newItem = numberOfItems(inSection: newSection) - 1
let newIndexPath: IndexPath = [newSection, newItem]
if numberOfItems(inSection: newSection) == 0 {
// If the section is empty, we need to try the previous section.
return index(before: newIndexPath)
}
else {
return newIndexPath
}
}
func index(after i: IndexPath) -> IndexPath {
if i.item + 1 < numberOfItems(inSection: i.section) {
return [i.section, i.item + 1]
}
if i.section + 1 < numberOfSections {
let newIndexPath: IndexPath = [i.section + 1, 0]
if numberOfItems(inSection: newIndexPath.section) == 0 {
// If the section is empty, we need to try the next section.
return index(after: newIndexPath)
}
else {
return newIndexPath
}
}
return [numberOfSections, 0]
}
subscript(i: IndexPath) -> IndexPath {
return i
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment