In this tutorial, you will learn how to create a UICollectionView
programmatically in Swift, set its layout, item size, background color, and item background color, and implement the didSelectItemAtIndexPath
delegate method to handle user taps on items. This tutorial is designed for beginners, so I’ll break down each step into simple, understandable parts.
Step 1: Conform to UICollectionViewDataSource and UICollectionViewDelegate Protocols
To provide data to the collection view and handle user interactions, your ViewController
class must conform to the UICollectionViewDataSource
and UICollectionViewDelegate
protocols. This means your class must implement the required methods defined by these protocols.
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate { // ViewController code will go here }
- The
UICollectionViewDataSource
protocol is responsible for providing the data that the collection view needs to display its cells, such as the number of items and the cell configuration for each item. - The
UICollectionViewDelegate
protocol allows your class to respond to user interactions with the collection view, such as selecting an item.
Step 2: Create UICollectionView Programmatically
Within your viewWillAppear
method of your ViewController
, you’ll create a UICollectionView
programmatically.
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) }
In the above code, you configure the layout of the collection view, item spacing, and size, then create the collection view with this layout, set the view controller as its data source, and delegate.
You register a default cell class (UICollectionViewCell
) is for reuse identifier “MyCell”, and the set collection view’s background color to white. Finally, you add the collection view to the view controller’s view hierarchy to make it visible on the screen.
This process ensures the collection view displays items in a grid format with specific dimensions and spacing, handles user interactions, and is ready to be populated with data.
Step 3: Implement UICollectionViewDataSource Methods
Implement the numberOfItemsInSection
and cellForItemAt
methods from the UICollectionViewDataSource
protocol. These methods inform the collection view about the number of items it should display and how to configure each item.
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 }
To set the background color of each item in your collection view, you can do so within the cellForItemAt
method of your UICollectionViewDataSource
.
Step 4: Implement the UICollectionViewDelegate Method
To handle user taps on items, implement the didSelectItemAt
method from the UICollectionViewDelegate
protocol. This method will be called when a user taps on an item, allowing you to respond accordingly.
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { print("User tapped on item \(indexPath.row)") }
Complete Code Example
Here’s how all the steps come together in a complete example.
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. } }
Conclusion
I hope this tutorial was helpful for you. There are a lot more Swift code examples on this website 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.