PPCollectionViewLayout.swift 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import UIKit
  2. /**
  3. Custom layout that allows for smooth resize animation.
  4. */
  5. class PPCollectionViewLayout: UICollectionViewLayout {
  6. public var viewWidth: CGFloat = 0.0
  7. public var spacing: CGFloat = 6.0
  8. public weak var itemsInfoProvider: (UICollectionViewDataSource & UICollectionViewDelegateFlowLayout)!
  9. private var attributes: [UICollectionViewLayoutAttributes] = []
  10. private var contentSize = CGSize.zero
  11. override func prepare() {
  12. super.prepare()
  13. attributes = []
  14. var origin = CGPoint()
  15. let itemsCount = itemsInfoProvider.collectionView(collectionView!, numberOfItemsInSection: 0)
  16. for index in 0..<itemsCount {
  17. let indexPath = IndexPath(item: index, section: 0)
  18. let itemAttributes = UICollectionViewLayoutAttributes(forCellWith: indexPath)
  19. let size = itemsInfoProvider.collectionView!(collectionView!, layout: self, sizeForItemAt: indexPath)
  20. itemAttributes.frame = CGRect(origin: origin, size: size)
  21. attributes.append(itemAttributes)
  22. origin.x = itemAttributes.frame.maxX + spacing
  23. }
  24. contentSize = CGSize(width: origin.x - spacing, height: origin.y)
  25. }
  26. override var collectionViewContentSize: CGSize {
  27. return contentSize
  28. }
  29. override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
  30. var layoutAttributes: [UICollectionViewLayoutAttributes] = []
  31. for itemAttributes in attributes {
  32. if (rect.intersects(itemAttributes.frame) == true) {
  33. layoutAttributes.append(itemAttributes)
  34. }
  35. }
  36. return layoutAttributes
  37. }
  38. override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
  39. if (attributes.count > indexPath.row) {
  40. return attributes[indexPath.row]
  41. } else {
  42. return nil
  43. }
  44. }
  45. override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
  46. return false
  47. }
  48. }