In this Swift code example, you will learn how to create and display UICollectionView in Swift Programmatically.
The Swift code example in this tutorial will cover the following:
- Create UICollectionView programmatically,
- Set UICollectionView layout UIEdgeInsets,
- Set UICollectionView item size(width and height),
- Set UICollectionView background color,
- Set UICollectionView Item background-color,
- Implement UICollectionView Delegate method didSelectItemAtIndexPath to handle an event when the user taps on one of the collection view items
Creating UICollectionView Programmatically
Below is a very simple code example in Swift that creates UICollectionView programmatically.
import UIKit class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 20, left: 10, bottom: 10, right: 10) layout.itemSize = CGSize(width: 60, height: 60) let myCollectionView:UICollectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) myCollectionView.dataSource = self myCollectionView.delegate = self myCollectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "MyCell") myCollectionView.backgroundColor = UIColor.white self.view.addSubview(myCollectionView) } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 100 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let myCell = collectionView.dequeueReusableCell(withReuseIdentifier: "MyCell", for: indexPath) myCell.backgroundColor = UIColor.blue return myCell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("User tapped on item \(indexPath.row)") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
I hope this code example was helpful for you. There are a lot more Swift code examples on this web site if you check the Swift Code Examples page.
Additionally, you might also want to check a list of recent Swift tutorials where you will also find a list of useful resources for iOS mobile app developers.