0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

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

Last updated at Posted at 2021-08-15

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

simulator_screenshot_4C5C79E2-9E70-4A5C-A989-3FAE112A802E.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?