When implementing a collection view, a vital step is creating its cell. The goal of this article is that by the time you have reached its last line, you will be able to create and customize your collection view cell. Let's get started!
- Firstly, we need to create a collection view cell.
- You can modify your collection view cell through the Editor Code and Editor Design, which work exactly as explained in their introduction articles.
- Let's go to Editor Design and press the top view. As we can see, we can change the size of our cell. Unlike the table view cell, we can alter both height and width of a collection view cell. The functionality of the dynamic size switch will be addressed Advanced Customisation: Collection View Cell article.
We will set our cell's width to 140 and height to 150.
Since we are in the mood to play, let's add an image view with the image of a concert and a label that says "My very own collection view cell".
- In Editor Code > Protocols > Recommended functions you have access to these three functions:
1. awakeFromNib: it is called as soon as you create the cell.
2. prepareForReuse: collection view cells are "recycled" when the user is scrolling through the table view. To avoid any wrong data displaying, you can "reset" all your subviews to their initial state at prepareForReuse.
3. setSelected: is triggered every time the cell is selected or deselected. Can be used for customisation of the design in a specific selected state.
What do you say we implement the setSelected state, so that when the user selects the cell, the background colour is set to yellow and the label instead of "My very own collection view cell" says "I am the selected cell"?
It seems we are ready to roll! Let's see the ending result!
And let's press a few cells to test the setSelected function.
Your very first collection view cell is ready!