Introduction to UICollectionView and Swift3
Steps to create UICollectionView in Swift 3
Create single view application, at this moment you have 3 files. Open ViewController.swift file and create an IBOutlet for our UICollectionView (We will drag and drop UICollectionView to view in storyboard in next step )
Open Main.storyboard and drag UICollectionView to the View Conroller Scene. Connect our IBOutlet, created in last step with UICollectionView.
Create a new UICollectionViewCell class and named it DummyCell (Check-mark “Also create xib file”). Open DummyCell.xib and give it height and width as shown in the image below.
Create UICollectionViewCell with xib |
Set height and with for UICollectionViewCell |
Drag UILabel to DummyCell.xib and open DummyCell.swift. Create IBOutlet for UILabel, we dragged on DummyCell.xib file.
Open DummyCell.xib and connect IBOutlet with UILabel.
Open ViewController.swift, and create UICollectionViewFlowLayout. Flowlayout is used to tell
UICollectionView following things
- Scroll Direction
- Item Spacing
- line Spacing
- Size for the cell or item
As we have UIFlowLayout created for our UICollectionView, it’s time to register nib for our UICollectionView. This tells the compiler that which xib is going to be used to create cell for UICollectionView. We will also create UICollectionViewDataSource methods/functions to populate our UICollectionView.
Complete Code for UICollectionView using Swift3