[Swift] Try using Collection View


I recently started learning Swift. We are developing a little thing as part of our learning. Since I used CollectionView for the first time in development, I will summarize what I learned about this.

Development environment

What is Collection View in the first place?

CollectionView is used when you want to display many items as a list like a panel as shown in the image below.

※reference image スクリーンショット 2021-01-12 23.24.59.png

Let's actually use it

First, set up Collection View

スクリーンショット 2021-01-12 23.11.51.png

After installation, set the cell identifier. This time, let's call it cell. スクリーンショット 2021-01-12 23.22.37.png

Installation of UI Label

Place the Label on the cell. Set the Label Tag after installation. By setting Tag, you can access the UI parts of each cell. スクリーンショット 2021-01-12 23.40.34.png

Add UICollectionViewDelegate and UICollectionViewDataSource

To use CollectionView, add UICollectionViewDelegate and UICollectionViewDataSource.

Also, when you add it, add the methods that need to be implemented. (Press Fix to complete it) スクリーンショット 2021-01-13 21.29.04.png

//Returns the number of cells in the section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    //This time it will be 12 for the time being. (If the data you want to display in the array is included, you can return the number of data in the array.)
    return 12
//Describe the content to be displayed in the cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    //Generate a cell on the storyboard Set the one attached by the identifier of the storyboard here
    let cell:UICollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
    //Tag on cell(1)Generate a UI Label with
    let label = cell.contentView.viewWithTag(1) as! UILabel
    //This time, simply reflect the cell number in the label text.
    label.text = String(indexPath.row + 1)
    return cell

Associate ViewController and CollectionView

In the part where the hierarchy of viewController of storyboard is displayed, right-click CollectionView and associate dataSource and delegate with ViewController.

スクリーンショット 2021-01-13 21.55.26.png

Up to this point, at least cells are displayed as shown in the image below. (You can check it easily by changing the background color of the cell. Also, if you do not adjust the position of the label, it will not be displayed well on the cell)

スクリーンショット 2021-01-12 23.24.59.png

When building, I got into the following error and struggled a little.

Could not cast value of type 'UIView' to 'UILabel'

When I investigated the cause, it seemed that I made a mistake in the place to attach the tag. As mentioned above, it is okay if you can set the Tag in the Label, but I think that this error occurred because you accidentally set the Tag in the ContentView part. When setting the Tag, make sure to check it carefully before setting it.

I want to resize the cell!

The cell size is small as it is now, so I want to change the size! In such a case, you can adjust the cells (adjust the cell size, adjust the distance between cells) by using UICollectionViewDelegateFlowLayout.

スクリーンショット 2021-01-13 22.22.19.png

Use this method to specify the cell size.

//Process to specify cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    //Horizontal space adjustment
    let horizontalSpace:CGFloat = 5

    //Specify the cell size. If you want to display 3 cells on the screen, the width of the device is divided into 3 parts.-Space between cells*2 (because there are two spaces between cells)
    let cellSize:CGFloat = self.view.bounds.width/3 - horizontalSpace*2
    //Width to return as a square,Make height the same
    return CGSize(width: cellSize, height: cellSize)
スクリーンショット 2021-01-12 23.24.59.png

If you want to display two cells in one row, you can change it as follows. (Note that the number of line spacing is one)

et cellSize:CGFloat = self.view.bounds.width/2 - horizontalSpace

I want to make a screen transition when I tap a cell!

In such a case, it can be implemented by using the didSelectItemAt method. (Assumption that Segway is connected to the transition destination view controller)

//Processing when selecting a cell
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    //Transition to the specified transition destination (minimum processing)
    performSegue(withIdentifier: "Specified Identifier", sender: nil)


This time I used CollectionView for the first time, so I tried to summarize it briefly. To be honest, I haven't really understood it yet, so I will continue to study!

I started studying Swift, and I became aware of how the apps I usually use are made, which is very educational. Someday, I will continue to move my hands and make various things so that the developed application can be published on the App Store and used by other people.

that's all.

Recommended Posts

[Swift] Try using Collection View
Try using libGDX
(For beginners) Swift UI view element collection
Try using powermock-mockito2-2.0.2
Try using GraalVM
Try using jmockit 1.48
Try using sql-migrate
Try using SwiftLint
Try using Log4j 2.0
Swift extension collection
Try using Axon Framework
Try using JobScheduler's REST-API
Try using java.lang.Math methods
Try using PowerMock's WhiteBox
Try using Talend Part 2
Try using Talend Part 1
Try using F # list
Try using each_with_index method
Try using Spring JDBC
Try using RocksDB in Java
[Swift] switch statement using tuples
Try using GloVe with Deeplearning4j
Try using view_component with rails
Try using Cocoa from Ruby
Try using letter_opener_web for inquiries
[Swift] After installing Scroll View
[Swift] Share data using AppDelegate
Try using IntelliJ IDEA once
Try using Spring Boot Security
[Swift] Asynchronous processing using PromiseKit
Try using gRPC in Ruby
[Rails] Try using Faraday middleware
[Processing] Try using GT Force.
[Swift UI] Use Map view
[Programming Encyclopedia] §2 Try using Ruby
[Swift] Implement UITableView using xib
People using docker Try using docker-compose
[Swift] Templates and explanations of basic functions using Map Kit View
Try using Redmine on Mac docker
Try using Redis with Java (jar)
[Java] Try to implement using generics
Try using the messaging system Pulsar
Try using IBM Java method tracing
Try using Hyperledger Iroha's Java SDK
[Java] Where did you try using java?
Try to display a slightly rich Webview in Swift UI using UIViewRepresentable