【iOS14】UITableViewをUICollectionViewに書き換える練習


UITableViewが非推奨の方向らしい?

資料を参考にすれど、む・・・むずかしい。

こういうときは、簡単なサンプルを書いてみようと思い
そういう事をされている方の記事を見つけました。

こちらの記事を参考させて頂き、今回はセクションを使わない
UICollectionLayoutListConfiguration.Appearance.plain
なものを作りたかったので、改変した結果がこちらです。

自分の分かる範囲では、Sectionは完全に消せなかったのでIntにして
layoutConfig.headerMode = .none としてみました。

【新しい疑問点】
dataSourceは新しくなったけどdelegateはそのまま?
=> そのままらしい

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!

    let data = ["A", "B", "C"]

    var collectionViewDataSource: UICollectionViewDiffableDataSource<Int, String>!

    override func viewDidLoad() {
        super.viewDidLoad()

        var layoutConfig = UICollectionLayoutListConfiguration(appearance: .plain)
        layoutConfig.headerMode = .none

        let layout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
        collectionView.collectionViewLayout = layout

        collectionViewDataSource = createDataSource()
        reloadList()
    }

    func createDataSource() -> UICollectionViewDiffableDataSource<Int, String> {
        let normalCell = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, indexPath, text) in
            var content = cell.defaultContentConfiguration()
            content.text = text
            cell.contentConfiguration = content
        }

        return UICollectionViewDiffableDataSource<Int, String>(collectionView: collectionView) {
            (collectionView, indexPath, text) -> UICollectionViewCell? in

            return collectionView.dequeueConfiguredReusableCell(using: normalCell, for: indexPath, item: text)
        }
    }

    func reloadList() {
        var snapshot = NSDiffableDataSourceSnapshot<Int, String>()
        snapshot.appendSections([0])
        snapshot.appendItems(data)
        collectionViewDataSource.apply(snapshot)
    }
}