Skip to content

Instantly share code, notes, and snippets.

@arashkashi
Created October 1, 2017 09:46
Show Gist options
  • Save arashkashi/c468bcec20c9e5ea1272f369d8a0ce73 to your computer and use it in GitHub Desktop.
Save arashkashi/c468bcec20c9e5ea1272f369d8a0ce73 to your computer and use it in GitHub Desktop.
based on visible cells of a collection view, extract which page and how many per page should be fetched
typealias PageInfo = (page: Int16, perPage: Int16)
class SwiftyCollectionCell: UICollectionViewCell {
var row: Int16 = 0
}
extension Collection where Iterator.Element == SwiftyCollectionCell {
func pageInfo(total: Int16 = Int16.max) -> PageInfo? {
let maxPerPage: Int16 = 20
guard self.count != 0 else { return nil }
let rows = self.map { $0.row }
let min = rows.min()!
var max = rows.max()!
guard min < total && max < total else { return nil }
max = [max, total].min()!
max = [min + maxPerPage, max].min()!
if min == 0 { return nil }
if min == 1 { return (page: 1, perPage: [maxPerPage, total].min()!) }
if min == max { max = min + [maxPerPage/2, total].min()! }
var perPage = max - min
var page = min / perPage
while (min / perPage) * perPage + perPage < max || min % perPage == 0 {
perPage = perPage + 1
page = min / perPage
}
assert(perPage <= 60)
return (page: page + 1, perPage: perPage)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment