Last active
May 16, 2019 14:00
-
-
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/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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