An object that adopts the UICollectionViewDataSource protocol is responsible for providing the data and views required by a collection view. A data source object represents your app’s data model and vends information to the collection view as needed. It also handles the creation and configuration of cells and supplementary views used by the collection view to display your data.


protocol UICollectionViewDataSource


At a minimum, all data source objects must implement the collectionView(_:numberOfItemsInSection:) and collectionView(_:cellForItemAt:) methods. These methods are responsible for returning the number of items in the collection view along with the items themselves. The remaining methods of the protocol are optional and only needed if your collection view organizes items into multiple sections or provides headers and footers for a given section.

When configuring the collection view object, assign your data source to its dataSource property. For more information about how a collection view works with its data source to present content, see UICollectionView.


Getting Item and Section Metrics

func collectionView(UICollectionView, numberOfItemsInSection: Int) -> Int

Asks your data source object for the number of items in the specified section.


func numberOfSections(in: UICollectionView) -> Int

Asks your data source object for the number of sections in the collection view.

Getting Views for Items

func collectionView(UICollectionView, cellForItemAt: IndexPath) -> UICollectionViewCell

Asks your data source object for the cell that corresponds to the specified item in the collection view.


func collectionView(UICollectionView, viewForSupplementaryElementOfKind: String, at: IndexPath) -> UICollectionReusableView

Asks your data source object to provide a supplementary view to display in the collection view.

Reordering Items

func collectionView(UICollectionView, canMoveItemAt: IndexPath) -> Bool

Asks your data source object whether the specified item can be moved to another location in the collection view.

func collectionView(UICollectionView, moveItemAt: IndexPath, to: IndexPath)

Tells your data source object to move the specified item to its new location.

Configuring an Index

func indexTitles(for: UICollectionView) -> [String]?

Asks the data source to return the titles for the index items to display for the collection view.

func collectionView(UICollectionView, indexPathForIndexTitle: String, at: Int) -> IndexPath

Asks the data source to return the index path of a collection view item that corresponds to one of your index entries.

See Also


protocol UICollectionViewDataSourcePrefetching

A protocol that provides advance warning of the data requirements for a collection view, allowing the triggering of asynchronous data load operations.

Asynchronously Loading Images into Table and Collection Views

Store and fetch images asynchronously to make your app more responsive.