Skip to content

Instantly share code, notes, and snippets.

@digoreis
Created March 23, 2017 19:53
Show Gist options
  • Save digoreis/743739908f68f1eec9be223183b35d3e to your computer and use it in GitHub Desktop.
Save digoreis/743739908f68f1eec9be223183b35d3e to your computer and use it in GitHub Desktop.
CircularQueue+UICollectionView
import UIKit
import PlaygroundSupport
class CircularQueue<T> : IteratorProtocol, RandomAccessCollection {
typealias Element = T
public typealias Index = Int
public typealias Indices = CountableRange<Int>
var position = 0
let items : [T]
init(items:[T]){
self.items = items
}
func next() -> T? {
let item = items[position]
position = ((position + 1) % items.count)
return item
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return items.count
}
public func index(after i: Int) -> Int {
_precondition(i == startIndex)
return endIndex
}
public func index(before i: Int) -> Int {
_precondition(i == endIndex)
return startIndex
}
public subscript(position: Int) -> Element {
get {
let pos = (position % items.count)
return items[pos]
}
set {
}
}
}
class CollectionViewController : UICollectionViewController {
let arrColor : [UIColor] = [.green,.yellow,.blue,.purple,.orange]
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = .white
self.collectionView?.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "PlayCell")
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 10000
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PlayCell", for: indexPath)
let queue = CircularQueue(items: arrColor)
cell.backgroundColor = queue[indexPath.row]
return cell
}
}
PlaygroundPage.current.liveView = CollectionViewController(collectionViewLayout: UICollectionViewFlowLayout())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment