What is UICollectionView?
UICollectionView
is a powerful UI component in iOS used to display a grid or list of items. It is highly flexible and customizable, making it perfect for photo galleries, carousels, lists, and custom layouts.
1. Creating a Basic UICollectionView
A. Adding UICollectionView in Storyboard
- Open Main.storyboard.
- Drag and drop a
UICollectionView
onto yourViewController
. - Set its constraints to fit the screen.
- Add a UICollectionViewCell in the Collection View.
- Set a Reuse Identifier (e.g.,
"cell"
) in the Attributes Inspector. - Connect the
UICollectionView
toViewController.swift
:@IBOutlet weak var collectionView: UICollectionView!
B. Setting Up UICollectionView in Code
import UIKit
class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
let items = ["🍎", "🍌", "🍇", "🍉", "🍊", "🍓", "🥭", "🍍", "🍑", "🥝"]
override func viewDidLoad() {
super.viewDidLoad()
// Set delegate and data source
collectionView.delegate = self
collectionView.dataSource = self
}
// Number of items in section
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items.count
}
// Create and configure cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.label.text = items[indexPath.row]
return cell
}
// Set cell size
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 100, height: 100)
}
}
✅ Explanation:
- Sets up UICollectionView with a simple array of emoji items.
- Defines delegate & data source methods.
- Configures cell size dynamically.
2. Creating a Custom UICollectionViewCell
- Create a new Swift file →
MyCollectionViewCell.swift
. - Design a Custom Cell in Storyboard:
- Select
UICollectionViewCell
in the storyboard. - Set the Identifier to
"cell"
. - Add a UILabel inside the cell.
- Connect the UILabel to
MyCollectionViewCell.swift
.
- Select
- MyCollectionViewCell.swift
import UIKit
class MyCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var label: UILabel!
}
✅ Explanation:
- Creates a custom cell with a label to display text or images.
3. Handling User Interaction (Tap)
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print("Selected item: \(items[indexPath.row])")
}
✅ Explanation:
- Prints the selected item’s name when tapped.
4. Dynamic Grid Layout Using FlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = (collectionView.frame.width - 30) / 3
return CGSize(width: width, height: width)
}
✅ Explanation:
- Automatically adjusts cell size to fit a 3-column grid.
5. Loading Images in UICollectionView
let images = ["image1.jpg", "image2.jpg", "image3.jpg"]
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.imageView.image = UIImage(named: images[indexPath.row])
return cell
}
✅ Explanation:
- Displays images from the asset catalog.
6. Adding Section Headers in UICollectionView
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let header = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "header", for: indexPath) as! MyCollectionHeaderView
header.titleLabel.text = "Fruits"
return header
}
✅ Explanation:
- Adds a header (e.g.,
"Fruits"
) above sections.
7. Horizontal Scrolling UICollectionView
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.scrollDirection = .horizontal
}
✅ Explanation:
- Changes the collection view to scroll sideways.
8. Pagination (Infinite Scrolling)
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView.contentOffset.y + scrollView.frame.size.height > scrollView.contentSize.height - 100 {
loadMoreData()
}
}
func loadMoreData() {
print("Loading more items...")
// Fetch more data and reload collectionView
}
✅ Explanation:
- Loads more items when scrolling to the bottom.
9. UICollectionView with Diffable Data Source (iOS 13+)
var dataSource: UICollectionViewDiffableDataSource<Section, String>!
enum Section {
case main
}
override func viewDidLoad() {
super.viewDidLoad()
dataSource = UICollectionViewDiffableDataSource<Section, String>(collectionView: collectionView) { (collectionView, indexPath, item) -> UICollectionViewCell? in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
cell.label.text = item
return cell
}
var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
snapshot.appendSections([.main])
snapshot.appendItems(items)
dataSource.apply(snapshot, animatingDifferences: true)
}
✅ Explanation:
- Uses
UICollectionViewDiffableDataSource
for efficient updates.
10. Summary of UICollectionView Features
Feature | Code Example |
---|---|
Basic Setup | UICollectionViewDataSource, UICollectionViewDelegate |
Custom Cell | UICollectionViewCell with UILabel/ImageView |
Dynamic Grid Layout | UICollectionViewDelegateFlowLayout |
User Interaction | didSelectItemAt indexPath |
Horizontal Scrolling | layout.scrollDirection = .horizontal |
Pagination | scrollViewDidScroll |
Diffable Data Source | NSDiffableDataSourceSnapshot |
Conclusion
UICollectionView
is a versatile and powerful UI component for displaying items efficiently in a grid or list. It is highly customizable and supports animations, dynamic layouts, and infinite scrolling.
Would you like a custom UICollectionView design for a specific app feature? 🚀