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

版本记录

版本号 时间
V1.0 2019.11.06 星期三

前言

iOS中有关视图控件用户能看到的都在UIKit框架里面,用户交互也是通过UIKit进行的。感兴趣的参考上面几篇文章。
1. UIKit框架(一) —— UIKit动力学和移动效果(一)
2. UIKit框架(二) —— UIKit动力学和移动效果(二)
3. UIKit框架(三) —— UICollectionViewCell的扩张效果的实现(一)
4. UIKit框架(四) —— UICollectionViewCell的扩张效果的实现(二)
5. UIKit框架(五) —— 自定义控件:可重复使用的滑块(一)
6. UIKit框架(六) —— 自定义控件:可重复使用的滑块(二)
7. UIKit框架(七) —— 动态尺寸UITableViewCell的实现(一)
8. UIKit框架(八) —— 动态尺寸UITableViewCell的实现(二)
9. UIKit框架(九) —— UICollectionView的数据异步预加载(一)
10. UIKit框架(十) —— UICollectionView的数据异步预加载(二)
11. UIKit框架(十一) —— UICollectionView的重用、选择和重排序(一)
12. UIKit框架(十二) —— UICollectionView的重用、选择和重排序(二)
13. UIKit框架(十三) —— 如何创建自己的侧滑式面板导航(一)
14. UIKit框架(十四) —— 如何创建自己的侧滑式面板导航(二)
15. UIKit框架(十五) —— 基于自定义UICollectionViewLayout布局的简单示例(一)
16. UIKit框架(十六) —— 基于自定义UICollectionViewLayout布局的简单示例(二)
17. UIKit框架(十七) —— 基于自定义UICollectionViewLayout布局的简单示例(三)
18. UIKit框架(十八) —— 基于CALayer属性的一种3D边栏动画的实现(一)
19. UIKit框架(十九) —— 基于CALayer属性的一种3D边栏动画的实现(二)
20. UIKit框架(二十) —— 基于UILabel跑马灯类似效果的实现(一)
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布局,感兴趣的给个赞或者关注~~~

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,456评论 5 477
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,370评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,337评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,583评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,596评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,572评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,936评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,595评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,850评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,601评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,685评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,371评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,951评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,934评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,167评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 43,636评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,411评论 2 342

推荐阅读更多精彩内容