Implement the UICollectionView of iOS14 with the minimum required code.

Trigger

A new API has been added to UICollectionView in WWDC2020, and I am very grateful that various people have written the outline and detailed functions! However, I don't understand my lack of understanding or how to write it concretely. ・ I don't understand the whole picture of the code ... I had a lot of trouble, so maybe there are other people who have the same difficulty! I thought it was an article.

Implementation image

All chords

ViewController.swift


class ViewController: UIViewController {

    @IBOutlet weak var collectionView: UICollectionView!
    
    enum Section: CaseIterable {
        case kanto
        case kyusyu
    }
    
    let data: [Section: [String]] = [
        .kanto: ["Kanto", "Tokyo", "Chiba"],
        .kyusyu: ["Kyusyu", "Fukuoka", "Miyazaki"]
    ]

    var collectionViewDataSource: UICollectionViewDiffableDataSource<Section, String>!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        var layoutConfig = UICollectionLayoutListConfiguration(appearance: .grouped)
        layoutConfig.headerMode = UICollectionLayoutListConfiguration.HeaderMode.firstItemInSection

        let layout = UICollectionViewCompositionalLayout.list(using: layoutConfig)
        collectionView.collectionViewLayout = layout
        
        collectionViewDataSource = createDataSource()
        reloadList()
    }
    

    func createDataSource() -> UICollectionViewDiffableDataSource<Section, String> {
        let normalCell = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, indexPath, text) in
            var content = cell.defaultContentConfiguration()
            content.text = text
            cell.contentConfiguration = content
        }
        
        return UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) {
            (collectionView, indexPath, text) -> UICollectionViewCell? in
        
            return collectionView.dequeueConfiguredReusableCell(using: normalCell, for: indexPath, item: text)
        }
    }
    
    func reloadList(){
        var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
        snapshot.appendSections(Section.allCases)
        snapshot.appendItems(data[.kanto]!, toSection: .kanto)
        snapshot.appendItems(data[.kyusyu]!, toSection: .kyusyu)
        collectionViewDataSource.apply(snapshot)
    }
}

Boil

Display data definition

enum Section: CaseIterable {
    case kanto
    case kyusyu
}

let data: [Section: [String]] = [
    .kanto: ["Kanto", "Tokyo", "Chiba"],
    .kyusyu: ["Kyusyu", "Fukuoka", "Miyazaki"]
]

Here, the data to be displayed is defined. data The very first" Kanto "and" Kyusyu "are section titles. (As you can see in the implementation image, the sections are automatically capitalized.)

Layout settings

var layoutConfig = UICollectionLayoutListConfiguration(appearance: .insetGrouped)
layoutConfig.headerMode = UICollectionLayoutListConfiguration.HeaderMode.firstItemInSection

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

Here, the layout of the collectionView is set. This time I am using the layout that can be used by default, but I plan to change this area when customizing the cell size etc. HeaderMode.firstItemInSection ← This is the setting that treats the beginning of the data as the section title.

Cell settings

func createDataSource() -> UICollectionViewDiffableDataSource<Section, String> {
	let normalCell = UICollectionView.CellRegistration<UICollectionViewListCell, String> { (cell, indexPath, text) in
		var content = cell.defaultContentConfiguration()
		content.text = text
		cell.contentConfiguration = content
	}
	
	return UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) {
		(collectionView, indexPath, text) -> UICollectionViewCell? in
	
		return collectionView.dequeueConfiguredReusableCell(using: normalCell, for: indexPath, item: text)
	}
}

Here, we set how to display the passed data. Of the traditional ʻUICollectionViewDataSource func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell` It has the same role as.

normalCell is a variable for registering cells in collectionView. The outlook is better because you can register and set the cell at the same time.

Data update

func reloadList(){
	var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
	snapshot.appendSections(Section.allCases)
	snapshot.appendItems(data[.kanto]!, toSection: .kanto)
	snapshot.appendItems(data[.kyusyu]!, toSection: .kyusyu)
	collectionViewDataSource.apply(snapshot)
}

The data defined first is displayed on the screen by ʻapply` to the collectionView.

Summary

I have a desire to write the section title in a better way, but I was able to write it more clearly than before. This article uses only basic UICollectionView features, so I'll write more advanced articles in other articles.

Please LGTM if you like because it will be encouraging \ (^ o ^) /

Recommended Posts

Implement the UICollectionView of iOS14 with the minimum required code.
Implement UICollectionView of iOS14 with CustomCell.
How to implement UICollectionView in Swift with code only
Specify the character code of the source when building with Maven
Try Hello World with the minimum configuration of Heroku Java spring-boot
Android application: Let's explain the mechanism of screen transition with simple code
[swift5] How to change the color of TabBar or the color of item of TabBar with code
Check the contents of params with pry
Implement the box ball system with Processing
About the treatment of BigDecimal (with reflection)
Format the contents of LocalDate with DateTimeFormatter
[Implementation] Eliminate the ominous smell of code
[IOS] Casually implement the semi-forced update mechanism
[Code] Forcibly breaks through the C problem "* 3 or / 2" of [AtCoder Problem-ABC100] with Java [Code]
Verify the contents of the argument object with Mockito
[Java] Explanation of Strategy pattern (with sample code)
Manage the version of Ruby itself with rbenv
Overwrite the contents of config with Spring-boot + JUnit5
The story of tuning android apps with libGDX
RSpec-Results of reviewing the test code for'users validation'
Calculate the similarity score of strings with JAVA
[Ruby] Code to display the day of the week
Implement the Like feature in Ajax with Rails.
Prepare the environment of CentOS 8 with Sakura VPS
Specify the default value with @Builder of Lombok
Measure the distance of the maze with breadth-first search
Profile-derived automation of Code Artifact authentication with Gradle
I checked the number of taxis with Ruby
The procedure I did when I prepared the environment of gradle + Java with VS Code (Windows 10)
[Swift] I tried to implement Instagram profile-like UI with UICollectionView only with code without storyboard
Let's implement a function to limit the number of access to the API with SpringBoot + Redis
Let's experience the authorization code grant flow with Spring Security OAuth-Part 1: Review of OAuth 2.0