UIKit框架(三十一) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的簡單示例(二)

版本記錄

版本號 時間
V1.0 2019.11.06 星期三

前言

iOS中有關視圖控件用戶能看到的都在UIKit框架里面丑掺,用戶交互也是通過UIKit進行的。感興趣的參考上面幾篇文章盟蚣。
1. UIKit框架(一) —— UIKit動力學和移動效果(一)
2. UIKit框架(二) —— UIKit動力學和移動效果(二)
3. UIKit框架(三) —— UICollectionViewCell的擴張效果的實現(xiàn)(一)
4. UIKit框架(四) —— UICollectionViewCell的擴張效果的實現(xiàn)(二)
5. UIKit框架(五) —— 自定義控件:可重復使用的滑塊(一)
6. UIKit框架(六) —— 自定義控件:可重復使用的滑塊(二)
7. UIKit框架(七) —— 動態(tài)尺寸UITableViewCell的實現(xiàn)(一)
8. UIKit框架(八) —— 動態(tài)尺寸UITableViewCell的實現(xiàn)(二)
9. UIKit框架(九) —— UICollectionView的數(shù)據(jù)異步預加載(一)
10. UIKit框架(十) —— UICollectionView的數(shù)據(jù)異步預加載(二)
11. UIKit框架(十一) —— UICollectionView的重用封字、選擇和重排序(一)
12. UIKit框架(十二) —— UICollectionView的重用、選擇和重排序(二)
13. UIKit框架(十三) —— 如何創(chuàng)建自己的側滑式面板導航(一)
14. UIKit框架(十四) —— 如何創(chuàng)建自己的側滑式面板導航(二)
15. UIKit框架(十五) —— 基于自定義UICollectionViewLayout布局的簡單示例(一)
16. UIKit框架(十六) —— 基于自定義UICollectionViewLayout布局的簡單示例(二)
17. UIKit框架(十七) —— 基于自定義UICollectionViewLayout布局的簡單示例(三)
18. UIKit框架(十八) —— 基于CALayer屬性的一種3D邊欄動畫的實現(xiàn)(一)
19. UIKit框架(十九) —— 基于CALayer屬性的一種3D邊欄動畫的實現(xiàn)(二)
20. UIKit框架(二十) —— 基于UILabel跑馬燈類似效果的實現(xiàn)(一)
21. UIKit框架(二十一) —— UIStackView的使用(一)
22. UIKit框架(二十二) —— 基于UIPresentationController的自定義viewController的轉場和展示(一)
23. UIKit框架(二十三) —— 基于UIPresentationController的自定義viewController的轉場和展示(二)
24. UIKit框架(二十四) —— 基于UICollectionViews和Drag-Drop在兩個APP間的使用示例 (一)
25. UIKit框架(二十五) —— 基于UICollectionViews和Drag-Drop在兩個APP間的使用示例 (二)
26. UIKit框架(二十六) —— UICollectionView的自定義布局 (一)
27. UIKit框架(二十七) —— UICollectionView的自定義布局 (二)
28. UIKit框架(二十八) —— 一個UISplitViewController的簡單實用示例 (一)
29. UIKit框架(二十九) —— 一個UISplitViewController的簡單實用示例 (二)
30. UIKit框架(三十) —— 基于UICollectionViewCompositionalLayout API的UICollectionViews布局的簡單示例(一)

源碼

1. Swift

首先看下工程組織結構

下面就是代碼了

1. PhotoDetailViewController.swift
import UIKit

class PhotoDetailViewController: UIViewController {
  var photoURL: URL?
  let imageView = UIImageView()

  convenience init(photoURL: URL) {
    self.init()
    self.photoURL = photoURL;
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    if let photoURL = photoURL {
      let imageName = photoURL.lastPathComponent
      navigationItem.title = imageName

      let image = UIImage(contentsOfFile: photoURL.path)
      imageView.image = image;
      imageView.contentMode = .scaleAspectFit

      imageView.translatesAutoresizingMaskIntoConstraints = false
      view.addSubview(imageView)
      view.backgroundColor = .systemBackground

      NSLayoutConstraint.activate([
        imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
        imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
        imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
        imageView.topAnchor.constraint(equalTo: view.topAnchor)
      ])
    }
  }
}
2. StringExtension.swift
import Foundation

extension StringProtocol {
  var firstUppercased: String {
    return prefix(1).uppercased() + dropFirst()
  }

  var displayNicely: String {
    return firstUppercased.replacingOccurrences(of: "_", with: " ")
  }
}
3. FileManagerExtensions.swift
import Foundation

extension FileManager {
  func albumsAtURL(_ fileURL: URL) throws -> [AlbumItem] {
    let albumsArray = try self.contentsOfDirectory(
      at: fileURL,
      includingPropertiesForKeys: [.nameKey, .isDirectoryKey],
      options: .skipsHiddenFiles
    ).filter { (url) -> Bool in
      do {
        let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
        return resourceValues.isDirectory! && url.lastPathComponent.first != "_"
      } catch { return false }
    }.sorted(by: { (urlA, urlB) -> Bool in
      do {
        let nameA = try urlA.resourceValues(forKeys:[.nameKey]).name
        let nameB = try urlB.resourceValues(forKeys: [.nameKey]).name
        return nameA! < nameB!
      } catch { return true }
    })

    return albumsArray.map { fileURL -> AlbumItem in
      do {
        let detailItems = try self.albumDetailItemsAtURL(fileURL)
        return AlbumItem(albumURL: fileURL, imageItems: detailItems)
      } catch {
        return AlbumItem(albumURL: fileURL)
      }
    }
  }

  func albumDetailItemsAtURL(_ fileURL: URL) throws -> [AlbumDetailItem] {
    guard let components = URLComponents(url: fileURL, resolvingAgainstBaseURL: false) else { return [] }

    let photosArray = try self.contentsOfDirectory(
      at: fileURL,
      includingPropertiesForKeys: [.nameKey, .isDirectoryKey],
      options: .skipsHiddenFiles
    ).filter { (url) -> Bool in
      do {
        let resourceValues = try url.resourceValues(forKeys: [.isDirectoryKey])
        return !resourceValues.isDirectory!
      } catch { return false }
    }.sorted(by: { (urlA, urlB) -> Bool in
      do {
        let nameA = try urlA.resourceValues(forKeys:[.nameKey]).name
        let nameB = try urlB.resourceValues(forKeys: [.nameKey]).name
        return nameA! < nameB!
      } catch { return true }
    })

    return photosArray.map { fileURL in AlbumDetailItem(
      photoURL: fileURL,
      thumbnailURL: URL(fileURLWithPath: "\(components.path)thumbs/\(fileURL.lastPathComponent)")
      )}
  }
}
4. SyncingBadgeView.swift
import UIKit

class SyncingBadgeView: UICollectionReusableView {
  static let reuseIdentifier = "syncing-badge"
  let imageView = UIImageView(image: #imageLiteral(resourceName: "syncIcon"))

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
    startAnimating()
  }

  required init?(coder: NSCoder) {
    fatalError("Not implemented")
  }
}

extension SyncingBadgeView {
  func configure() {
    backgroundColor = .white

    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFill
    imageView.clipsToBounds = true
    addSubview(imageView)

    let inset = CGFloat(2)
    NSLayoutConstraint.activate([
      imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset),
      imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset),
      imageView.topAnchor.constraint(equalTo: topAnchor, constant: inset),
      imageView.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset)
    ])

    let radius = bounds.width / 2.0
    layer.cornerRadius = radius
    layer.borderColor = UIColor.black.cgColor
    layer.borderWidth = 1.0
  }

  func startAnimating() {
    let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
    rotation.toValue = Double.pi * 2
    rotation.duration = 1
    rotation.isCumulative = true
    rotation.repeatCount = Float.greatestFiniteMagnitude
    imageView.layer.add(rotation, forKey: "rotationAnimation")
  }
}
5. HeaderView.swift
import UIKit

class HeaderView: UICollectionReusableView {
  static let reuseIdentifier = "header-reuse-identifier"

  let label = UILabel()

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

  required init?(coder: NSCoder) {
    fatalError()
  }
}

extension HeaderView {
  func configure() {
    backgroundColor = .systemBackground

    addSubview(label)
    label.translatesAutoresizingMaskIntoConstraints = false
    label.adjustsFontForContentSizeCategory = true

    let inset = CGFloat(10)
    NSLayoutConstraint.activate([
      label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: inset),
      label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -inset),
      label.topAnchor.constraint(equalTo: topAnchor, constant: inset),
      label.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -inset)
    ])
    label.font = UIFont.preferredFont(forTextStyle: .title3)
  }
}
6. AlbumDetailViewController.swift
import UIKit

class AlbumDetailViewController: UIViewController {
  static let syncingBadgeKind = "syncing-badge-kind"

  enum Section {
    case albumBody
  }

  var dataSource: UICollectionViewDiffableDataSource<Section, AlbumDetailItem>! = nil
  var albumDetailCollectionView: UICollectionView! = nil

  var albumURL: URL?

  convenience init(withPhotosFromDirectory directory: URL) {
    self.init()
    albumURL = directory
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = albumURL?.lastPathComponent.displayNicely
    configureCollectionView()
    configureDataSource()
  }
}

extension AlbumDetailViewController {
  func configureCollectionView() {
    let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: generateLayout())
    view.addSubview(collectionView)
    collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    collectionView.backgroundColor = .systemBackground
    collectionView.delegate = self
    collectionView.register(PhotoItemCell.self, forCellWithReuseIdentifier: PhotoItemCell.reuseIdentifer)
    collectionView.register(SyncingBadgeView.self,
                            forSupplementaryViewOfKind: AlbumDetailViewController.syncingBadgeKind,
                            withReuseIdentifier: SyncingBadgeView.reuseIdentifier)
    albumDetailCollectionView = collectionView
  }

  func configureDataSource() {
    dataSource = UICollectionViewDiffableDataSource
      <Section, AlbumDetailItem>(collectionView: albumDetailCollectionView) {
        (collectionView: UICollectionView, indexPath: IndexPath, detailItem: AlbumDetailItem) -> UICollectionViewCell? in
        guard let cell = collectionView.dequeueReusableCell(
          withReuseIdentifier: PhotoItemCell.reuseIdentifer,
          for: indexPath) as? PhotoItemCell else { fatalError("Could not create new cell") }
        cell.photoURL = detailItem.thumbnailURL
        return cell
    }

    dataSource.supplementaryViewProvider = {
      (
      collectionView: UICollectionView,
      kind: String,
      indexPath: IndexPath) -> UICollectionReusableView? in

      let hasSyncBadge = indexPath.row % Int.random(in: 1...6) == 0

      if let badgeView = collectionView.dequeueReusableSupplementaryView(
        ofKind: kind,
        withReuseIdentifier: SyncingBadgeView.reuseIdentifier,
        for: indexPath) as? SyncingBadgeView {

        badgeView.isHidden = !hasSyncBadge
        return badgeView
      } else {
        fatalError("Cannot create new supplementary")
      }
    }

    // load our initial data
    let snapshot = snapshotForCurrentState()
    dataSource.apply(snapshot, animatingDifferences: false)
  }

  func generateLayout() -> UICollectionViewLayout {
    // We have three row styles
    // Style 1: 'Full'
    // A full width photo
    // Style 2: 'Main with pair'
    // A 2/3 width photo with two 1/3 width photos stacked vertically
    // Style 3: 'Triplet'
    // Three 1/3 width photos stacked horizontally

    // Syncing badge
    let syncingBadgeAnchor = NSCollectionLayoutAnchor(edges: [.top, .trailing], fractionalOffset: CGPoint(x: -0.3, y: 0.3))
    let syncingBadge = NSCollectionLayoutSupplementaryItem(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .absolute(20),
        heightDimension: .absolute(20)),
      elementKind: AlbumDetailViewController.syncingBadgeKind,
      containerAnchor: syncingBadgeAnchor)

    // Full
    let fullPhotoItem = NSCollectionLayoutItem(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalWidth(2/3)),
      supplementaryItems: [syncingBadge])
    fullPhotoItem.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2)

    // Main with pair
    let mainItem = NSCollectionLayoutItem(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(2/3),
        heightDimension: .fractionalHeight(1.0)))
    mainItem.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2)

    let pairItem = NSCollectionLayoutItem(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalHeight(0.5)))
    pairItem.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2)
    let trailingGroup = NSCollectionLayoutGroup.vertical(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1/3),
        heightDimension: .fractionalHeight(1.0)),
      subitem: pairItem,
      count: 2)

    let mainWithPairGroup = NSCollectionLayoutGroup.horizontal(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalWidth(4/9)),
      subitems: [mainItem, trailingGroup])

    // Triplet
    let tripletItem = NSCollectionLayoutItem(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1/3),
        heightDimension: .fractionalHeight(1.0)))
    tripletItem.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2)

    let tripletGroup = NSCollectionLayoutGroup.horizontal(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalWidth(2/9)),
      subitems: [tripletItem, tripletItem, tripletItem])

    // Reversed main with pair
    let mainWithPairReversedGroup = NSCollectionLayoutGroup.horizontal(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalWidth(4/9)),
      subitems: [trailingGroup, mainItem])

    let nestedGroup = NSCollectionLayoutGroup.vertical(
      layoutSize: NSCollectionLayoutSize(
        widthDimension: .fractionalWidth(1.0),
        heightDimension: .fractionalWidth(16/9)),
      subitems: [fullPhotoItem, mainWithPairGroup, tripletGroup, mainWithPairReversedGroup])

    let section = NSCollectionLayoutSection(group: nestedGroup)
    let layout = UICollectionViewCompositionalLayout(section: section)
    return layout
  }

  func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<Section, AlbumDetailItem> {
    var snapshot = NSDiffableDataSourceSnapshot<Section, AlbumDetailItem>()
    snapshot.appendSections([Section.albumBody])
    let items = itemsForAlbum()
    snapshot.appendItems(items)
    return snapshot
  }

  func itemsForAlbum() -> [AlbumDetailItem] {
    guard let albumURL = albumURL else { return [] }
    let fileManager = FileManager.default
    do {
      return try fileManager.albumDetailItemsAtURL(albumURL)
    } catch {
      print(error)
      return []
    }
  }
}

extension AlbumDetailViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
    let photoDetailVC = PhotoDetailViewController(photoURL: item.photoURL)
    navigationController?.pushViewController(photoDetailVC, animated: true)
  }
}
7. PhotoItemCell.swift
import UIKit

class PhotoItemCell: UICollectionViewCell {
  static let reuseIdentifer = "photo-item-cell-reuse-identifier"
  let imageView = UIImageView()
  let contentContainer = UIView()

  var photoURL: URL? {
    didSet {
      configure()
    }
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

extension PhotoItemCell {
  func configure() {
    contentContainer.translatesAutoresizingMaskIntoConstraints = false
    contentView.addSubview(contentContainer)

    guard let photoURL = self.photoURL else { return };
    let photo = UIImage(contentsOfFile: photoURL.path)
    imageView.image = photo

    imageView.translatesAutoresizingMaskIntoConstraints = false
    contentContainer.addSubview(imageView)

    NSLayoutConstraint.activate([
      contentContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      contentContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      contentContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
      contentContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),

      imageView.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor),
      imageView.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor),
      imageView.bottomAnchor.constraint(equalTo: contentContainer.bottomAnchor),
      imageView.topAnchor.constraint(equalTo: contentContainer.topAnchor)
    ])
  }
}
8. AlbumDetailItem.swift
import Foundation

class AlbumDetailItem: Hashable {
  let photoURL: URL
  let thumbnailURL: URL
  let subitems: [AlbumDetailItem]

  init(photoURL: URL, thumbnailURL: URL, subitems: [AlbumDetailItem] = []) {
    self.photoURL = photoURL
    self.thumbnailURL = thumbnailURL
    self.subitems = subitems
  }

  func hash(into hasher: inout Hasher) {
    hasher.combine(identifier)
  }

  static func == (lhs: AlbumDetailItem, rhs: AlbumDetailItem) -> Bool {
    return lhs.identifier == rhs.identifier
  }

  private let identifier = UUID()
}
9. AlbumsViewController.swift
import UIKit

class AlbumsViewController: UIViewController {
  static let sectionHeaderElementKind = "section-header-element-kind"

  enum Section: String, CaseIterable {
    case featuredAlbums = "Featured Albums"
    case sharedAlbums = "Shared Albums"
    case myAlbums = "My Albums"
  }

  var dataSource: UICollectionViewDiffableDataSource<Section, AlbumItem>! = nil
  var albumsCollectionView: UICollectionView! = nil

  var baseURL: URL?

  convenience init(withAlbumsFromDirectory directory: URL) {
    self.init()
    baseURL = directory
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    navigationItem.title = "Your Albums"
    configureCollectionView()
    configureDataSource()
  }
}

extension AlbumsViewController {
  func configureCollectionView() {
    let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: generateLayout())
    view.addSubview(collectionView)
    collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
    collectionView.backgroundColor = .systemBackground
    collectionView.delegate = self
    collectionView.register(AlbumItemCell.self, forCellWithReuseIdentifier: AlbumItemCell.reuseIdentifer)
    collectionView.register(FeaturedAlbumItemCell.self, forCellWithReuseIdentifier: FeaturedAlbumItemCell.reuseIdentifer)
    collectionView.register(SharedAlbumItemCell.self, forCellWithReuseIdentifier: SharedAlbumItemCell.reuseIdentifer)
    collectionView.register(
      HeaderView.self,
      forSupplementaryViewOfKind: AlbumsViewController.sectionHeaderElementKind,
      withReuseIdentifier: HeaderView.reuseIdentifier)
    albumsCollectionView = collectionView
  }

  func configureDataSource() {
    dataSource = UICollectionViewDiffableDataSource
      <Section, AlbumItem>(collectionView: albumsCollectionView) {
        (collectionView: UICollectionView, indexPath: IndexPath, albumItem: AlbumItem) -> UICollectionViewCell? in

        let sectionType = Section.allCases[indexPath.section]
        switch sectionType {
        case .featuredAlbums:
          guard let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: FeaturedAlbumItemCell.reuseIdentifer,
            for: indexPath) as? FeaturedAlbumItemCell else { fatalError("Could not create new cell") }
          cell.featuredPhotoURL = albumItem.imageItems[0].thumbnailURL
          cell.title = albumItem.albumTitle
          cell.totalNumberOfImages = albumItem.imageItems.count
          return cell

        case .sharedAlbums:
          guard let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: SharedAlbumItemCell.reuseIdentifer,
            for: indexPath) as? SharedAlbumItemCell else { fatalError("Could not create new cell") }
          cell.featuredPhotoURL = albumItem.imageItems[0].thumbnailURL
          cell.title = albumItem.albumTitle
          return cell

        case .myAlbums:
          guard let cell = collectionView.dequeueReusableCell(
            withReuseIdentifier: AlbumItemCell.reuseIdentifer,
            for: indexPath) as? AlbumItemCell else { fatalError("Could not create new cell") }
          cell.featuredPhotoURL = albumItem.imageItems[0].thumbnailURL
          cell.title = albumItem.albumTitle
          return cell

        }
    }
    
    dataSource.supplementaryViewProvider = { (
      collectionView: UICollectionView,
      kind: String,
      indexPath: IndexPath) -> UICollectionReusableView? in

      guard let supplementaryView = collectionView.dequeueReusableSupplementaryView(
        ofKind: kind,
        withReuseIdentifier: HeaderView.reuseIdentifier,
        for: indexPath) as? HeaderView else { fatalError("Cannot create header view") }

      supplementaryView.label.text = Section.allCases[indexPath.section].rawValue
      return supplementaryView
    }

    let snapshot = snapshotForCurrentState()
    dataSource.apply(snapshot, animatingDifferences: false)
  }

  func generateLayout() -> UICollectionViewLayout {
    let layout = UICollectionViewCompositionalLayout { (sectionIndex: Int,
      layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
      let isWideView = layoutEnvironment.container.effectiveContentSize.width > 500

      let sectionLayoutKind = Section.allCases[sectionIndex]
      switch (sectionLayoutKind) {
      case .featuredAlbums: return self.generateFeaturedAlbumsLayout(isWide: isWideView)
      case .sharedAlbums: return self.generateSharedlbumsLayout()
      case .myAlbums: return self.generateMyAlbumsLayout(isWide: isWideView)
      }
    }
    return layout
  }

  func generateFeaturedAlbumsLayout(isWide: Bool) -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                          heightDimension: .fractionalWidth(2/3))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    // Show one item plus peek on narrow screens, two items plus peek on wider screens
    let groupFractionalWidth = isWide ? 0.475 : 0.95
    let groupFractionalHeight: Float = isWide ? 1/3 : 2/3
    let groupSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(CGFloat(groupFractionalWidth)),
      heightDimension: .fractionalWidth(CGFloat(groupFractionalHeight)))
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: 1)
    group.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)

    let headerSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                            heightDimension: .estimated(44))
    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
      layoutSize: headerSize,
      elementKind: AlbumsViewController.sectionHeaderElementKind, alignment: .top)

    let section = NSCollectionLayoutSection(group: group)
    section.boundarySupplementaryItems = [sectionHeader]
    section.orthogonalScrollingBehavior = .groupPaging

    return section
  }

  func generateSharedlbumsLayout() -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1.0),
      heightDimension: .fractionalWidth(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)

    let groupSize = NSCollectionLayoutSize(
      widthDimension: .absolute(140),
      heightDimension: .absolute(186))
    let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitem: item, count: 1)
    group.contentInsets = NSDirectionalEdgeInsets(top: 5, leading: 5, bottom: 5, trailing: 5)

    let headerSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1.0),
      heightDimension: .estimated(44))
    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
      layoutSize: headerSize,
      elementKind: AlbumsViewController.sectionHeaderElementKind,
      alignment: .top)

    let section = NSCollectionLayoutSection(group: group)
    section.boundarySupplementaryItems = [sectionHeader]
    section.orthogonalScrollingBehavior = .groupPaging

    return section
  }

  func generateMyAlbumsLayout(isWide: Bool) -> NSCollectionLayoutSection {
    let itemSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1.0),
      heightDimension: .fractionalHeight(1.0))
    let item = NSCollectionLayoutItem(layoutSize: itemSize)
    item.contentInsets = NSDirectionalEdgeInsets(top: 2, leading: 2, bottom: 2, trailing: 2)

    let groupHeight = NSCollectionLayoutDimension.fractionalWidth(isWide ? 0.25 : 0.5)
    let groupSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1.0),
      heightDimension: groupHeight)
    let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: isWide ? 4 : 2)

    let headerSize = NSCollectionLayoutSize(
      widthDimension: .fractionalWidth(1.0),
      heightDimension: .estimated(44))
    let sectionHeader = NSCollectionLayoutBoundarySupplementaryItem(
      layoutSize: headerSize,
      elementKind: AlbumsViewController.sectionHeaderElementKind,
      alignment: .top)

    let section = NSCollectionLayoutSection(group: group)
    section.boundarySupplementaryItems = [sectionHeader]

    return section
  }

  func snapshotForCurrentState() -> NSDiffableDataSourceSnapshot<Section, AlbumItem> {
    let allAlbums = albumsInBaseDirectory()
    let sharingSuggestions = Array(albumsInBaseDirectory().prefix(3))
    let sharedAlbums = Array(albumsInBaseDirectory().suffix(3))

    var snapshot = NSDiffableDataSourceSnapshot<Section, AlbumItem>()
    snapshot.appendSections([Section.featuredAlbums])
    snapshot.appendItems(sharingSuggestions)

    snapshot.appendSections([Section.sharedAlbums])
    snapshot.appendItems(sharedAlbums)

    snapshot.appendSections([Section.myAlbums])
    snapshot.appendItems(allAlbums)
    return snapshot
  }

  func albumsInBaseDirectory() -> [AlbumItem] {
    guard let baseURL = baseURL else { return [] }

    let fileManager = FileManager.default
    do {
      return try fileManager.albumsAtURL(baseURL)
    } catch {
      print(error)
      return []
    }
  }
}

extension AlbumsViewController: UICollectionViewDelegate {
  func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
    let albumDetailVC = AlbumDetailViewController(withPhotosFromDirectory: item.albumURL)
    navigationController?.pushViewController(albumDetailVC, animated: true)
  }
}
10. AlbumItem.swift
import Foundation

class AlbumItem: Hashable {
  let albumURL: URL
  let albumTitle: String
  let imageItems: [AlbumDetailItem]

  init(albumURL: URL, imageItems: [AlbumDetailItem] = []) {
    self.albumURL = albumURL
    self.albumTitle = albumURL.lastPathComponent.displayNicely
    self.imageItems = imageItems
  }

  func hash(into hasher: inout Hasher) {
    hasher.combine(identifier)
  }

  static func == (lhs: AlbumItem, rhs: AlbumItem) -> Bool {
    return lhs.identifier == rhs.identifier
  }

  private let identifier = UUID()
}
11. AlbumItemCell.swift
import UIKit

class AlbumItemCell: UICollectionViewCell {
  static let reuseIdentifer = "album-item-cell-reuse-identifier"
  let titleLabel = UILabel()
  let featuredPhotoView = UIImageView()
  let contentContainer = UIView()

  var title: String? {
    didSet {
      configure()
    }
  }

  var featuredPhotoURL: URL? {
    didSet {
      configure()
    }
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

extension AlbumItemCell {
  func configure() {
    contentContainer.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(featuredPhotoView)
    contentView.addSubview(contentContainer)

    featuredPhotoView.translatesAutoresizingMaskIntoConstraints = false
    if let featuredPhotoURL = featuredPhotoURL {
      featuredPhotoView.image = UIImage(contentsOfFile: featuredPhotoURL.path)
    }
    featuredPhotoView.clipsToBounds = true
    contentContainer.addSubview(featuredPhotoView)

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = title
    titleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
    titleLabel.adjustsFontForContentSizeCategory = true
    titleLabel.textColor = .white
    titleLabel.textAlignment = .center
    titleLabel.layer.shadowColor = UIColor.black.cgColor
    titleLabel.layer.shadowRadius = 3.0
    titleLabel.layer.shadowOpacity = 1.0
    titleLabel.layer.shadowOffset = CGSize(width: 4, height: 4)
    titleLabel.layer.masksToBounds = false
    contentContainer.addSubview(titleLabel)

    NSLayoutConstraint.activate([
      contentContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      contentContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      contentContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
      contentContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),

      featuredPhotoView.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor),
      featuredPhotoView.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor),
      featuredPhotoView.topAnchor.constraint(equalTo: contentContainer.topAnchor),
      featuredPhotoView.bottomAnchor.constraint(equalTo: contentContainer.bottomAnchor),

      titleLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      titleLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
      titleLabel.centerYAnchor.constraint(equalTo: contentView.centerYAnchor)
    ])
  }
}
12. FeaturedAlbumItemCell.swift
import UIKit

class FeaturedAlbumItemCell: UICollectionViewCell {
  static let reuseIdentifer = "featured-album-item-cell-reuse-identifier"
  let titleLabel = UILabel()
  let imageCountLabel = UILabel()
  let featuredPhotoView = UIImageView()
  let contentContainer = UIView()

  var title: String? {
    didSet {
      configure()
    }
  }

  var totalNumberOfImages: Int? {
    didSet {
      configure()
    }
  }

  var featuredPhotoURL: URL? {
    didSet {
      configure()
    }
  }

  override init(frame: CGRect) {
    super.init(frame: frame)
    configure()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }
}

extension FeaturedAlbumItemCell {
  func configure() {
    contentContainer.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(featuredPhotoView)
    contentView.addSubview(contentContainer)

    featuredPhotoView.translatesAutoresizingMaskIntoConstraints = false
    if let featuredPhotoURL = featuredPhotoURL {
      featuredPhotoView.image = UIImage(contentsOfFile: featuredPhotoURL.path)
    }
    featuredPhotoView.layer.cornerRadius = 4
    featuredPhotoView.clipsToBounds = true
    contentContainer.addSubview(featuredPhotoView)

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = title
    titleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    titleLabel.adjustsFontForContentSizeCategory = true
    contentContainer.addSubview(titleLabel)

    imageCountLabel.translatesAutoresizingMaskIntoConstraints = false
    if let totalNumberOfImages = totalNumberOfImages {
      imageCountLabel.text = "\(totalNumberOfImages) photos"
    }
    imageCountLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    imageCountLabel.adjustsFontForContentSizeCategory = true
    imageCountLabel.textColor = .placeholderText
    contentContainer.addSubview(imageCountLabel)

    let spacing = CGFloat(10)
    NSLayoutConstraint.activate([
      contentContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      contentContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      contentContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
      contentContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),

      featuredPhotoView.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor),
      featuredPhotoView.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor),
      featuredPhotoView.topAnchor.constraint(equalTo: contentContainer.topAnchor),

      titleLabel.topAnchor.constraint(equalTo: featuredPhotoView.bottomAnchor, constant: spacing),
      titleLabel.leadingAnchor.constraint(equalTo: featuredPhotoView.leadingAnchor),
      titleLabel.trailingAnchor.constraint(equalTo: featuredPhotoView.trailingAnchor),

      imageCountLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor),
      imageCountLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      imageCountLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      imageCountLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
    ])
  }
}
13. SharedAlbumItemCell.swift
import UIKit

class SharedAlbumItemCell: UICollectionViewCell {
  static let reuseIdentifer = "shared-album-item-cell-reuse-identifier"
  let titleLabel = UILabel()
  let ownerLabel = UILabel()
  let featuredPhotoView = UIImageView()
  let ownerAvatar = UIImageView()
  let contentContainer = UIView()

  let owner: Owner;

  enum Owner: Int, CaseIterable {
    case Tom
    case Matt
    case Ray

    func avatar() -> UIImage {
      switch self {
      case .Tom: return #imageLiteral(resourceName: "tom_profile")
      case .Matt: return #imageLiteral(resourceName: "matt_profile")
      case .Ray: return #imageLiteral(resourceName: "ray_profile")
      }
    }

    func name() -> String {
      switch self {
      case .Tom: return "Tom Elliott"
      case .Matt: return "Matt Galloway"
      case .Ray: return "Ray Wenderlich"
      }
    }
  }

  var title: String? {
    didSet {
      configure()
    }
  }

  var featuredPhotoURL: URL? {
    didSet {
      configure()
    }
  }

  override init(frame: CGRect) {
    self.owner = Owner.allCases.randomElement()!
    super.init(frame: frame)
    configure()
  }

  required init?(coder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
  }

}

extension SharedAlbumItemCell {
  func configure() {
    contentContainer.translatesAutoresizingMaskIntoConstraints = false

    contentView.addSubview(featuredPhotoView)
    contentView.addSubview(contentContainer)

    featuredPhotoView.translatesAutoresizingMaskIntoConstraints = false
    if let featuredPhotoURL = featuredPhotoURL {
      featuredPhotoView.image = UIImage(contentsOfFile: featuredPhotoURL.path)
    }
    featuredPhotoView.layer.cornerRadius = 4
    featuredPhotoView.clipsToBounds = true
    contentContainer.addSubview(featuredPhotoView)

    titleLabel.translatesAutoresizingMaskIntoConstraints = false
    titleLabel.text = title
    titleLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    titleLabel.adjustsFontForContentSizeCategory = true
    contentContainer.addSubview(titleLabel)

    ownerLabel.translatesAutoresizingMaskIntoConstraints = false
    ownerLabel.text = "From \(owner.name())"
    ownerLabel.font = UIFont.preferredFont(forTextStyle: .subheadline)
    ownerLabel.adjustsFontForContentSizeCategory = true
    ownerLabel.textColor = .placeholderText
    contentContainer.addSubview(ownerLabel)

    ownerAvatar.translatesAutoresizingMaskIntoConstraints = false
    ownerAvatar.image = owner.avatar()
    ownerAvatar.layer.cornerRadius = 15
    ownerAvatar.layer.borderColor = UIColor.systemBackground.cgColor
    ownerAvatar.layer.borderWidth = 1
    ownerAvatar.clipsToBounds = true
    contentContainer.addSubview(ownerAvatar)

    let spacing = CGFloat(10)
    NSLayoutConstraint.activate([
      contentContainer.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      contentContainer.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      contentContainer.topAnchor.constraint(equalTo: contentView.topAnchor),
      contentContainer.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),

      featuredPhotoView.leadingAnchor.constraint(equalTo: contentContainer.leadingAnchor),
      featuredPhotoView.trailingAnchor.constraint(equalTo: contentContainer.trailingAnchor),
      featuredPhotoView.topAnchor.constraint(equalTo: contentContainer.topAnchor),

      titleLabel.topAnchor.constraint(equalTo: featuredPhotoView.bottomAnchor, constant: spacing),
      titleLabel.leadingAnchor.constraint(equalTo: featuredPhotoView.leadingAnchor),
      titleLabel.trailingAnchor.constraint(equalTo: featuredPhotoView.trailingAnchor),

      ownerLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor),
      ownerLabel.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
      ownerLabel.trailingAnchor.constraint(equalTo: contentView.trailingAnchor),
      ownerLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),

      ownerAvatar.heightAnchor.constraint(equalToConstant: 30),
      ownerAvatar.widthAnchor.constraint(equalToConstant: 30),
      ownerAvatar.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -spacing),
      ownerAvatar.bottomAnchor.constraint(equalTo: featuredPhotoView.bottomAnchor, constant: -spacing),
    ])
  }
}
14. AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
  var window: UIWindow?

  internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    self.window = UIWindow(frame: UIScreen.main.bounds)

    guard let bundleURL = Bundle.main.url(forResource: "PhotoData", withExtension: "bundle") else { return false }
    let initialViewController = AlbumsViewController(withAlbumsFromDirectory: bundleURL)

    let navigationController = UINavigationController(rootViewController: initialViewController)

    window?.rootViewController = navigationController
    window?.makeKeyAndVisible()

    return true
  }
}

題外話:你可以無縫銜接找到下一任碘橘,我卻不肯放過自己!

后記

本篇主要講述了基于UICollectionViewCompositionalLayout API的UICollectionViews布局吱肌,感興趣的給個贊或者關注~~~

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末痘拆,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子氮墨,更是在濱河造成了極大的恐慌纺蛆,老刑警劉巖吐葵,帶你破解...
    沈念sama閱讀 221,548評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異桥氏,居然都是意外死亡温峭,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,497評論 3 399
  • 文/潘曉璐 我一進店門字支,熙熙樓的掌柜王于貴愁眉苦臉地迎上來凤藏,“玉大人,你說我怎么就攤上這事祥款∏灞浚” “怎么了?”我有些...
    開封第一講書人閱讀 167,990評論 0 360
  • 文/不壞的土叔 我叫張陵刃跛,是天一觀的道長抠艾。 經(jīng)常有香客問我,道長桨昙,這世上最難降的妖魔是什么检号? 我笑而不...
    開封第一講書人閱讀 59,618評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮蛙酪,結果婚禮上齐苛,老公的妹妹穿的比我還像新娘。我一直安慰自己桂塞,他們只是感情好凹蜂,可當我...
    茶點故事閱讀 68,618評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著阁危,像睡著了一般玛痊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上狂打,一...
    開封第一講書人閱讀 52,246評論 1 308
  • 那天擂煞,我揣著相機與錄音,去河邊找鬼趴乡。 笑死对省,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的晾捏。 我是一名探鬼主播蒿涎,決...
    沈念sama閱讀 40,819評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼惦辛!你這毒婦竟也來了劳秋?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,725評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎俗批,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體市怎,經(jīng)...
    沈念sama閱讀 46,268評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡岁忘,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,356評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了区匠。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片干像。...
    茶點故事閱讀 40,488評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖驰弄,靈堂內(nèi)的尸體忽然破棺而出麻汰,到底是詐尸還是另有隱情,我是刑警寧澤戚篙,帶...
    沈念sama閱讀 36,181評論 5 350
  • 正文 年R本政府宣布五鲫,位于F島的核電站,受9級特大地震影響岔擂,放射性物質(zhì)發(fā)生泄漏位喂。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,862評論 3 333
  • 文/蒙蒙 一乱灵、第九天 我趴在偏房一處隱蔽的房頂上張望塑崖。 院中可真熱鬧,春花似錦痛倚、人聲如沸规婆。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,331評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽抒蚜。三九已至,卻和暖如春颠区,著一層夾襖步出監(jiān)牢的瞬間削锰,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,445評論 1 272
  • 我被黑心中介騙來泰國打工毕莱, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留器贩,地道東北人。 一個月前我還...
    沈念sama閱讀 48,897評論 3 376
  • 正文 我出身青樓朋截,卻偏偏與公主長得像蛹稍,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子部服,可洞房花燭夜當晚...
    茶點故事閱讀 45,500評論 2 359

推薦閱讀更多精彩內(nèi)容