The UICollectionView class manages an ordered collection of data items and presents them using customizable layouts. Collection views provide the same general function as table views except that a collection view is able to support more than just single-column layouts. Collection views support customizable layouts that can be used to implement multi-column grids, tiled layouts, circular layouts, and many more. You can even change the layout of a collection view dynamically if you want.

When adding a collection view to your user interface, your app’s main job is to manage the data associated with that collection view. The collection view gets its data from the data source object, which is an object that conforms to the UICollectionViewDataSourceprotocol and is provided by your app. Data in the collection view is organized into individual items, which can then be grouped into sections for presentation. An item is the smallest unit of data you want to present. For example, in a photos app, an item might be a single image. The collection view presents items onscreen using a cell, which is an instance of the UICollectionViewCell class that your data source configures and provides.

In addition to its cells, a collection view can present data using other types of views too. These supplementary views can be things like section headers and footers that are separate from the individual cells but still convey some sort of information. Support for supplementary views is optional and defined by the collection view’s layout object, which is also responsible for defining the placement of those views.

Besides embedding it in your user interface, you use the methods of UICollectionView object to ensure that the visual presentation of items matches the order in your data source object. Thus, whenever you add, delete, or rearrange data in your collection, you use the methods of this class to insert, delete, and rearrange the corresponding cells. You also use the collection view object to manage the selected items, although for this behavior the collection view works with its associated delegate object.

Collection Views and Layout Objects

A very important object associated with a collection view is the layout object, which is a subclass of the UICollectionViewLayout class. The layout object is responsible for defining the organization and location of all cells and supplementary views inside the collection view. Although it defines their locations, the layout object does not actually apply that information to the corresponding views. Because the creation of cells and supplementary views involves coordination between the collection view and your data source object, the collection view actually applies layout information to the views. Thus, in a sense, the layout object is like another data source, only providing visual information instead of item data.

You normally specify a layout object when creating a collection view but you can also change the layout of a collection view dynamically. The layout object is stored in the collectionViewLayout property. Setting this property directly updates the layout immediately, without animating the changes. If you want to animate the changes, you must call the setCollectionViewLayout:animated:completion: method instead.

If you want to create an interactive transition—one that is driven by a gesture recognizer or touch events—use the startInteractiveTransitionToCollectionViewLayout:completion: method to change the layout object. That method installs an intermediate layout object whose purpose is to work with your gesture recognizer or event-handling code to track the transition progress. When your event-handling code determines that the transition is finished, it calls the finishInteractiveTransition or cancelInteractiveTransition method to remove the intermediate layout object and install the intended target layout object.

Creating Cells and Supplementary Views

The collection view’s data source object provides both the content for items and the views used to present that content. When the collection view first loads its content, it asks its data source to provide a view for each visible item. To simplify the creation process for your code, the collection view requires that you always dequeue views, rather than create them explicitly in your code. There are two methods for dequeueing views. The one you use depends on which type of view has been requested:

Before you call either of these methods, you must tell the collection view how to create the corresponding view if one does not already exist. For this, you must register either a class or a nib file with the collection view. For example, when registering cells, you use the registerClass:forCellWithReuseIdentifier: or registerNib:forCellWithReuseIdentifier: method. As part of the registration process, you specify the reuse identifier that identifies the purpose of the view. This is the same string you use when dequeueing the view later.

After dequeueing the appropriate view in your delegate method, configure its content and return it to the collection view for use. After getting the layout information from the layout object, the collection view applies it to the view and displays it.

Declaration

Parameters

frame

The frame rectangle for the collection view, measured in points. The origin of the frame is relative to the superview in which you plan to add it. This frame is passed to the superclass during initialization.

layout

The layout object to use for organizing items. The collection view stores a strong reference to the specified object. Must not be nil.

Return Value

An initialized collection view object or nil if the object could not be created.

Discussion

Use this method when initializing a collection view object programmatically.

Declaration

Discussion

The view (if any) in this property is positioned underneath all of the other content and sized automatically to fill the entire bounds of the collection view. The background view does not scroll with the collection view’s other content. The collection view maintains a strong reference to the background view object.

This property is nil by default, which displays the background color of the collection view.

Parameters

The reuse identifier to associate with the specified class. This parameter must not be nil and must not be an empty string.

Discussion

Prior to calling the dequeueReusableCellWithReuseIdentifier:forIndexPath: method of the collection view, you must use this method or the registerNib:forCellWithReuseIdentifier: method to tell the collection view how to create a new cell of the given type. If a cell of the specified type is not currently in a reuse queue, the collection view uses the provided information to create a new cell object automatically.

If you previously registered a class or nib file with the same reuse identifier, the class you specify in the cellClass parameter replaces the old entry. You may specify nil for cellClass if you want to unregister the class from the specified reuse identifier.

Declaration

Parameters

The nib object containing the cell object. The nib file must contain only one top-level object and that object must be of the type UICollectionViewCell.

identifier

The reuse identifier to associate with the specified nib file. This parameter must not be nil and must not be an empty string.

Discussion

Prior to calling the dequeueReusableCellWithReuseIdentifier:forIndexPath: method of the collection view, you must use this method or the registerClass:forCellWithReuseIdentifier: method to tell the collection view how to create a new cell of the given type. If a cell of the specified type is not currently in a reuse queue, the collection view uses the provided information to create a new cell object automatically.

If you previously registered a class or nib file with the same reuse identifier, the object you specify in the nib parameter replaces the old entry. You may specify nil for nib if you want to unregister the nib file from the specified reuse identifier.

Parameters

The kind of supplementary view to create. This value is defined by the layout object. This parameter must not be nil.

identifier

The reuse identifier to associate with the specified class. This parameter must not be nil and must not be an empty string.

Discussion

Prior to calling the dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: method of the collection view, you must use this method or the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method to tell the collection view how to create a supplementary view of the given type. If a view of the specified type is not currently in a reuse queue, the collection view uses the provided information to create a view object automatically.

If you previously registered a class or nib file with the same element kind and reuse identifier, the class you specify in the viewClass parameter replaces the old entry. You may specify nil for viewClass if you want to unregister the class from the specified element kind and reuse identifier.

Parameters

nib

The nib object containing the view object. The nib file must contain only one top-level object and that object must be of the type UICollectionReusableView.

kind

The kind of supplementary view to create. The layout defines the types of supplementary views it supports. The value of this string may correspond to one of the predefined kind strings or to a custom string that the layout added to support a new type of supplementary view. This parameter must not be nil.

identifier

The reuse identifier to associate with the specified nib file. This parameter must not be nil and must not be an empty string.

Discussion

Prior to calling the dequeueReusableSupplementaryViewOfKind:withReuseIdentifier:forIndexPath: method of the collection view, you must use this method or the registerClass:forSupplementaryViewOfKind:withReuseIdentifier: method to tell the collection view how to create a supplementary view of the given type. If a view of the specified type is not currently in a reuse queue, the collection view uses the provided information to create a view object automatically.

If you previously registered a class or nib file with the same element kind and reuse identifier, the class you specify in the viewClass parameter replaces the old entry. You may specify nil for nib if you want to unregister the class from the specified element kind and reuse identifier.

Parameters

identifier

The reuse identifier for the specified cell. This parameter must not be nil.

indexPath

The index path specifying the location of the cell. The data source receives this information when it is asked for the cell and should just pass it along. This method uses the index path to perform additional configuration based on the cell’s position in the collection view.

Return Value

Discussion

Call this method from your data source object when asked to provide a new cell for the collection view. This method dequeues an existing cell if one is available or creates a new one based on the class or nib file you previously registered.

Important

You must register a class or nib file using the registerClass:forCellWithReuseIdentifier: or registerNib:forCellWithReuseIdentifier: method before calling this method.

If you registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithFrame: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.

Parameters

The kind of supplementary view to retrieve. This value is defined by the layout object. This parameter must not be nil.

identifier

The reuse identifier for the specified view. This parameter must not be nil.

indexPath

The index path specifying the location of the supplementary view in the collection view. The data source receives this information when it is asked for the view and should just pass it along. This method uses the information to perform additional configuration based on the view’s position in the collection view.

Return Value

Discussion

Call this method from your data source object when asked to provide a new supplementary view for the collection view. This method dequeues an existing view if one is available or creates a new one based on the class or nib file you previously registered.

Important

You must register a class or nib file using the registerClass:forSupplementaryViewOfKind:withReuseIdentifier: or registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method before calling this method. You can also register a set of default supplementary views with the layout object using the registerClass:forDecorationViewOfKind: or registerNib:forDecorationViewOfKind: method.

If you registered a class for the specified identifier and a new cell must be created, this method initializes the cell by calling its initWithFrame: method. For nib-based cells, this method loads the cell object from the provided nib file. If an existing cell was available for reuse, this method calls the cell’s prepareForReuse method instead.

Parameters

Specify YEStrue if you want to animate changes from the current layout to the new layout specified by the layout parameter. Specify NOfalse to make the change without animations.

completion

The block that is executed when the layout transition finishes or is aborted by the user. This block takes the following parameter:

finished

A Boolean indicating whether the transition completed successfully. This parameter is YEStrue if the transition finished and the new layout is installed. It is NOfalse if the user aborted the transition and returned to the old layout.

Discussion

This method initiates a layout change programmatically, notifying you when the transition is complete. If you choose to animate the layout change, the animation timing and parameters are controlled by the collection view.

Return Value

Discussion

Call this method when you want to change the layout of your collection view using an intermediate transition. When you call this method, the collection view quietly makes the returned transition layout object its current layout object. It is your responsibility to set up a gesture recognizer or other touch-event handling code to track the transition progress. As progress changes, update the transitionProgress property of the transition layout object and invalidate the layout. Invalidating its layout causes the transition layout object to update the position of items based on the new progress value.

When your event-handling code determines that the user has finished the transition to the new layout, call the finishInteractiveTransition method. If your code determines that the user has canceled the transition, call the cancelInteractiveTransition method to revert the changes instead. Calling either of these methods removes the transition layout object from the collection view and installs the appropriate target layout object.

Availability

See Also

Tells the collection view to finish an interactive transition by installing the intended target layout.

Declaration

Swift

funcfinishInteractiveTransition()

Objective-C

- (void)finishInteractiveTransition

Discussion

Call this method after a call to the startInteractiveTransitionToCollectionViewLayout:completion: method and after you determine through a gesture recognizer or other event-handling code that the user wants to transition to the new layout. This method removes the intermediate transition layout object from the collection view and installs the intended target layout object. It then performs any final animations to get the collection view’s items from their current positions to the positions specified by the newly installed layout object.

After calling this method, you can also remove the gesture recognizer or event-handling code you installed to manage the interactive portions of the transition.

Availability

See Also

Tells the collection view to abort an interactive transition and return to its original layout object.

Declaration

Swift

funccancelInteractiveTransition()

Objective-C

- (void)cancelInteractiveTransition

Discussion

Call this method after a call to the startInteractiveTransitionToCollectionViewLayout:completion: method and after you determine through a gesture recognizer or other event-handling code that the user wants to revert to the collection view’s original layout. This method removes the intermediate transition layout object from the collection view and reinstalls the original layout object. It then performs any final animations to get the collection view’s items from their current positions to the positions specified by the original layout object.

After calling this method, you can also remove the gesture recognizer or event-handling code you installed to manage the interactive portions of the transition.

Availability

See Also

Declaration

Swift

funcreloadData()

Objective-C

- (void)reloadData

Discussion

Call this method to reload all of the items in the collection view. This causes the collection view to discard any currently visible items and redisplay them. For efficiency, the collection view only displays those cells and supplementary views that are visible. If the collection data shrinks as a result of the reload, the collection view adjusts its scrolling offsets accordingly.

You should not call this method in the middle of animation blocks where items are being inserted or deleted. Insertions and deletions automatically cause the table’s data to be updated appropriately.

Declaration

Parameters

indexPaths

An array of NSIndexPath objects, each of which contains a section index and item index at which to insert a new cell. This parameter must not be nil.

Discussion

Call this method to insert one or more new items into the collection view. You might do this when your data source object receives data for new items or in response to user interactions with the collection view. The collection view gets the layout information for the new cells as part of calling this method. And if the layout information indicates that the cells should appear onscreen, the collection view asks your data source to provide the appropriate views, animating them into position as needed.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Declaration

Parameters

indexPath

The index path of the item you want to move. This parameter must not be nil.

newIndexPath

The index path of the item’s new location. This parameter must not be nil.

Discussion

Use this method to reorganize existing data items. You might do this when you rearrange the items within your data source object or in response to user interactions with the collection view. You can move items between sections or within the same section. The collection view updates the layout as needed to account for the move, animating cells into position as needed.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Declaration

Parameters

indexPaths

An array of NSIndexPath objects, each of which contains a section index and item index for the item you want to delete from the collection view. This parameter must not be nil.

Discussion

Use this method to remove items from the collection view. You might do this when you remove the items from your data source object or in response to user interactions with the collection view. The collection view updates the layout of the remaining items to account for the deletions, animating the remaining items into position as needed.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Declaration

Parameters

sections

An index set containing the indexes of the sections you want to insert. This parameter must not be nil.

Discussion

Use this method to insert one or more sections into the collection view. This method adds the sections, and it is up to your data source to report the number of items in each section when asked for the information. The collection view then uses that information to get updated layout attributes for the newly inserted sections and items. If the insertions cause a change in the collection view’s visible content, those changes are animated into place.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Declaration

Parameters

section

The index path of the section you want to move. This parameter must not be nil.

newSection

The index path of the section’s new location. This parameter must not be nil.

Discussion

Use this method to reorganize existing sections and their contained items. You might do this when you rearrange sections within your data source object or in response to user interactions with the collection view. The collection view updates the layout as needed to account for the move, animating new views into position as needed.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Declaration

Parameters

sections

The indexes of the sections you want to delete. This parameter must not be nil.

Discussion

Use this method to remove the sections and their items from the collection view. You might do this when you remove the sections from your data source object or in response to user interactions with the collection view. The collection view updates the layout of the remaining sections and items to account for the deletions, animating the remaining items into position as needed.

You can also call this method from a block passed to the performBatchUpdates:completion: method when you want to animate multiple separate changes into place at the same time. See the description of that method for more information.

Import Statement

Availability

A Boolean value that indicates whether users can select items in the collection view.

Declaration

Swift

var allowsSelection: Bool

Objective-C

@property(nonatomic)BOOLallowsSelection

Discussion

If the value of this property is YEStrue (the default), users can select items. If you want more fine-grained control over the selection of items, you must provide a delegate object and implement the appropriate methods of the UICollectionViewDelegate protocol.

Import Statement

Availability

See Also

A Boolean value that determines whether users can select more than one item in the collection view.

Declaration

Swift

var allowsMultipleSelection: Bool

Objective-C

@property(nonatomic)BOOLallowsMultipleSelection

Discussion

This property controls whether multiple items can be selected simultaneously. The default value of this property is NOfalse.

When the value of this property is YEStrue, tapping a cell adds it to the current selection (assuming the delegate permits the cell to be selected). Tapping the cell again removes it from the selection.

Discussion

If the allowsSelection property is NOfalse, calling this method has no effect. If there is an existing selection with a different index path and the allowsMultipleSelection property is NOfalse, calling this method replaces the previous selection.

This method does not cause any selection-related delegate methods to be called.

Declaration

Return Value

An array of NSIndexPath objects, each of which corresponds to a visible cell in the collection view. This array does not include any supplementary views that are currently visible. If there are no visible items, this method returns an empty array.

Parameters

kind

A string specifying the kind of supplementary view whose layout attributes you want. Layout classes are responsible for defining the kinds of supplementary views they support.

indexPath

The index path of the supplementary view. The interpretation of this value depends on how the layout implements the view. For example, a view associated with a section might contain just a section value.

Return Value

The layout attributes of the supplementary view or nil if the specified supplementary view does not exist.

Discussion

Use this method to retrieve the layout information for a particular supplementary view. You should always use this method instead of querying the layout object directly.

Parameters

updates

The block that performs the relevant insert, delete, reload, or move operations.

completion

A completion handler block to execute when all of the operations are finished. This block takes a single Boolean parameter that contains the value YEStrue if all of the related animations completed successfully or NOfalse if they were interrupted. This parameter may be nil.

Discussion

You can use this method in cases where you want to make multiple changes to the collection view in one single animated operation, as opposed to in several separate animations. You might use this method to insert, delete, reload, or move cells or use it to change the layout parameters associated with one or more cells. Use the blocked passed in the updates parameter to specify all of the operations you want to perform.

Deletes are processed before inserts in batch operations. This means the indexes for the deletions are processed relative to the indexes of the collection view’s state before the batch operation, and the indexes for the insertions are processed relative to the indexes of the state after all the deletions in the batch operation.

Declaration

Discussion

This completion block takes the following parameters:

completed

A Boolean indicating whether the animations ran to completion.

finish

A Boolean indicating whether the transition finished or was canceled. This parameter is YEStrue if the transition ran to completion and the new layout is installed. It is NOfalse if the user canceled the transition and the old layout is installed.

Constants

None

UICollectionViewScrollPositionNone

Do not scroll the item into view.

Available in iOS 6.0 and later.

Top

UICollectionViewScrollPositionTop

Scroll so that the item is positioned at the top of the collection view’s bounds. This option is mutually exclusive with the UICollectionViewScrollPositionCenteredVertically and UICollectionViewScrollPositionBottom options.

Available in iOS 6.0 and later.

CenteredVertically

UICollectionViewScrollPositionCenteredVertically

Scroll so that the item is centered vertically in the collection view. This option is mutually exclusive with the UICollectionViewScrollPositionTop and UICollectionViewScrollPositionBottom options.

Available in iOS 6.0 and later.

Bottom

UICollectionViewScrollPositionBottom

Scroll so that the item is positioned at the bottom of the collection view’s bounds. This option is mutually exclusive with the UICollectionViewScrollPositionTop and UICollectionViewScrollPositionCenteredVertically options.

Available in iOS 6.0 and later.

Left

UICollectionViewScrollPositionLeft

Scroll so that the item is positioned at the left edge of the collection view’s bounds. This option is mutually exclusive with the UICollectionViewScrollPositionCenteredHorizontally and UICollectionViewScrollPositionRight options.

Available in iOS 6.0 and later.

CenteredHorizontally

UICollectionViewScrollPositionCenteredHorizontally

Scroll so that the item is centered horizontally in the collection view. This option is mutually exclusive with the UICollectionViewScrollPositionLeft and UICollectionViewScrollPositionRight options.

Available in iOS 6.0 and later.

Right

UICollectionViewScrollPositionRight

Scroll so that the item is positioned at the right edge of the collection view’s bounds. This option is mutually exclusive with the UICollectionViewScrollPositionLeft and UICollectionViewScrollPositionCenteredHorizontally options.