Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 27 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save danielctull/6938b4516eaba29556e382f7f83b7534 to your computer and use it in GitHub Desktop.
Save danielctull/6938b4516eaba29556e382f7f83b7534 to your computer and use it in GitHub Desktop.
Wraps the six UICollectionViewFlowLayout delegate methods and their equivalent properties using functional programming techniques, so that values are easier to retrieve. Full details at: http://danieltull.co.uk/blog/2018/04/13/simplifying-uicollectionviewflowlayout-delegate-method-usage-with-functional-programming/
extension UICollectionViewFlowLayout {
typealias DelegateMethod<Key, Value> = ((UICollectionView, UICollectionViewLayout, Key) -> Value)
private var delegate: UICollectionViewDelegateFlowLayout? {
return collectionView?.delegate as? UICollectionViewDelegateFlowLayout
}
func retrieve<Key, Value>(
using delegateMethod: DelegateMethod<Key, Value>?,
key: Key,
fallback: @autoclosure () -> Value
) -> Value {
guard
let collectionView = collectionView,
let value = delegateMethod?(collectionView, self, key)
else {
return fallback()
}
return value
}
public func inset(for section: Int) -> UIEdgeInsets {
return retrieve(
using: delegate?.collectionView(_:layout:insetForSectionAt:),
key: section,
fallback: sectionInset)
}
public func sizeForItem(at indexPath: IndexPath) -> CGSize {
return retrieve(
using: delegate?.collectionView(_:layout:sizeForItemAt:),
key: indexPath,
fallback: itemSize)
}
public func minimumLineSpacing(for section: Int) -> CGFloat {
return retrieve(
using: delegate?.collectionView(_:layout:minimumLineSpacingForSectionAt:),
key: section,
fallback: minimumLineSpacing)
}
public func minimumInteritemSpacing(for section: Int) -> CGFloat {
return retrieve(
using: delegate?.collectionView(_:layout:minimumInteritemSpacingForSectionAt:),
key: section,
fallback: minimumInteritemSpacing)
}
public func referenceSizeForHeader(in section: Int) -> CGSize {
return retrieve(
using: delegate?.collectionView(_:layout:referenceSizeForHeaderInSection:),
key: section,
fallback: headerReferenceSize)
}
public func referenceSizeForFooter(in section: Int) -> CGSize {
return retrieve(
using: delegate?.collectionView(_:layout:referenceSizeForFooterInSection:),
key: section,
fallback: footerReferenceSize)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment