How to use UICollectionView in Swift?

iOSiPhone/iPadMobile DevelopmentSwift

To use collection view in swift, first, we need to create a collection View. We can either drag and drop it to the storyboard, or we can make it programmatically. After that, we need to confirm our class to UICollectionViewDataSource and UICollectionViewDelegate. Also if we need custom cell size and layouts, we need to confirm it to UICollectionViewDelegateFlowLayout.

Let’s see the step required to create a collection View programmatically.

func initCollection() {
   let layout = UICollectionViewFlowLayout()
   layout.itemSize = CGSize(width: 50, height: 50)
   let collection = UICollectionView.init(frame: self.view.frame, collectionViewLayout: layout)
   collection.dataSource = self
   collection.delegate = self
   collection.backgroundColor = colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
   collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
   self.view.addSubview(collection)
}

We need to call the above function in our ViewDidLoad() method. Whether we create a collection programmatically, or with a storyboard, we need to allocate data source, and delegate to give data to table, and observe its actions respectively.

Now, we need to tell the collection, how many sections it should have −

func numberOfSections(in collectionView: UICollectionView) -> Int {
   return 1
}

After that, we need to tell how many items it will have, and what data should be present in the cells.

func collectionView(_ collection: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   return 7
}
func collectionView(_ collection: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
   let cell = collection.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
   cell.layer.backgroundColor = colorLiteral(red: 0.4392156899, green: 0.01176470611, blue: 0.1921568662, alpha: 1)
   return cell
}

Optionally we can give it different size according to requirement.

func collectionView(_ collection: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
   let size = CGSize(width: 200, height: 50)
   return size
}

When we run the above code on a device, this is the result that’s produced.

raja
Published on 30-Jan-2019 10:04:37
Advertisements