How to use CollectionView in Swift

In this tutorial we will see how we can use UICollectionView in Swift for iOS app development

UICollectionView is very similar to the UITableView. UICollectionView can show multiple columns and it supports horizontal scrolling

Now we will build simple app to understand UICollectionView

(1) First create a single view application using XODE

(2) Now you can drag and drop the UICollectionView controller in to the View Controller of the storyborad

In this image you can see the UICollectionViewCell inside the UICollectionView. This can be seen at top left corner of the UICollectionView. You have to give value for identifier for this UICollectionViewCell

Select the UICollectionViewCell and then select the Attribute Inspector to give name for the identifier

(3) Add UICollectionViewDelegate and UICollectionViewDataSource Protocols
To work with UICollectionView, you need to add two protocols named UICollectionViewDelegate and UICollectionViewDataSource

(4) Conform Protocols
Now you have to conform protocol.
At a minimum, all data source objects must implement the collectionView(_:numberOfItemsInSection:) and collectionView(_:cellForItemAt:) methods.

So this method will return the number of items which collection view should have

And the following method will return the UICollectionViewCell. This method gets the UICollectionViewCell from the ReuseIdentifier whic you defined in Step 2. Also I have changed the color of the background of the cell

(5) Build and Run the Application
Now you can build and run the application to get the following screen

UICollectionView Screen