Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save NilStack/eb43c3051fdb3741dd4adff3e7c1e080 to your computer and use it in GitHub Desktop.
Save NilStack/eb43c3051fdb3741dd4adff3e7c1e080 to your computer and use it in GitHub Desktop.

Revisions

  1. @danielctull danielctull revised this gist Apr 14, 2018. No changes.
  2. @danielctull danielctull revised this gist Apr 14, 2018. No changes.
  3. @danielctull danielctull created this gist Apr 13, 2018.
    74 changes: 74 additions & 0 deletions UICollectionViewFlowLayout+DelegateAccess.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,74 @@

    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)
    }
    }