iOS Guides | Samples

UIKit.UICollectionView Class

Efficiently presents multiple UIViews on the screen using flexible layouts.

See Also: UICollectionView

Syntax

[Foundation.Register("UICollectionView", true)]
[ObjCRuntime.Introduced(ObjCRuntime.PlatformName.iOS, 6, 0, ObjCRuntime.PlatformArchitecture.None, null)]
public class UICollectionView : UIScrollView, IDisposable

See Also

Remarks

The UICollectionView is a container view that allows the application developer to lay out multiple items on the screen with more flexibility than is provided by a UITableView. It is a subtype of UIScrollView, so the layouts can span multiple pages. The layout used by the UICollectionView is controlled by it's UICollectionView.CollectionViewLayout property.

A UICollectionView must have a UICollectionViewLayout. The most commonly-used UICollectionViewLayout is UICollectionViewFlowLayout, which lays out its content views either horizontally or vertically until it reaches the bounds and then wraps around.

These grid-like layouts are very flexible and customizable, but because UICollectionView and UICollectionViewLayout are independent, simply providing a different UICollectionViewLayout can easily change the presentation style of the UICollectionView. The application developer can create custom layouts to support whatever layout can be imagined.

The patterns for providing data to a UICollectionView to create items and interact with those items follow the same delegation and data source patterns commonly used in iOS development.

Collection Views are more powerful than UITableViews, which are limited to a single column, but are also more complex. UITableView has certain built-in behaviors such as an editing mode, row animations, and easy-to-use headers and footers. If a UITableView satisfies the application's UI requirements, the application developer should prefer to use the UITableView.

A UICollectionView user interface involves a collaboration of different objects with different concerns:

ConcernDescriptionTypes
Content ManagementThe overall contents of the user interface

UICollectionView, UICollectionViewController

LayoutPosition and layout attributes of various component views

UICollectionViewLayout, UICollectionViewLayoutAttributes, UICollectionViewUpdateItem

Data ManagementData and event-management

UICollectionViewDataSource, UICollectionViewDelegate

Reusable viewsDefine component elements of the overall UICollectionView

UICollectionViewCell, UICollectionReusableView

UICollectionView Basics

A UICollectionView is made up of three different types of UIViews:

RoleDescriptionType
CellsData-driven views, each of a single item in the data set.UICollectionViewCell
Supplementary viewsData-driven views, each associated with a section. For example, header and footer views.UICollectionReusableView
Decoration viewsNon-data-driven views associated with the layout and overall view appearance. For example, the scrolling bookshelves background in the iBooks app and the Newsstand.UICollectionReusableView

The relationship between these three types of views is shown in the following image, based on the "Introduction to Collection Views" article. The cells are the orange-and-white rectangles and are laid out in a line. An instance of a supplementary view with a UIView.BackgroundColor of UIColor.Yellow separates sections, while a single decoration view provides a background for the entire UICollectionView.

(Background image by NASA, http://visibleearth.nasa.gov/)

Understanding the reuse queue

The UICollectionView is designed to work with large datasets. The two major attributes of this design are the "reuse queue" for component views and the UICollectionViewDataSource interface. The reuse queue is a system-managed collection of component views that minimizes memory consumption by only allocating those views that are on-screen and a handful of "next visible" screens. The following illustration, based on a variation of the code from the "Introduction to Collection Views" sample, shows how efficient this reuse queue is: 204 views are visible but the reuse queue only consists of 217 instances of the AnimalCell subtype of UICollectionViewCell. The dataset numbers in the thousands, but the number of actually allocated view components is minimal.

Not only does the reuse queue only have a minimal number of component views, it reuses component views rather than allocating and releasing off-screen views. This helps greatly with performance, but has important consequences for the application developer:

  • Component view types (or nibs) are registered with the UICollectionView, which is responsible for their memory.
  • Component view instances are reused and have their values re-assigned. Application developers must be cautious about assumptions made about references to such values, which will change as the application user scrolls.
  • The application developer must write the functions that (re-)assign these values: UICollectionViewDataSource.GetCell and, if supplementary views are desired, UICollectionViewDataSource.GetViewForSupplementaryElement.

The following code, from the "Introduction to Collection Views" sample, shows how component view types are registered and reassigned. Each component role type has an NSString identifier (for instance, the type AnimalCell, which is used for the cell role, has the identifier "AnimalCell", the others are not shown). The methods UICollectionView.RegisterClassForCell and UICollectionView.RegisterClassForSupplementaryView register the classes for the cell and supplementary view roles, while the method UICollectionViewLayout.RegisterClassForDecorationView registers the decoration view with the UICollectionViewLayout that is the UICollectionView's' UICollectionView.CollectionViewLayout property.

It is very important that you provide a constructor that takes a RectangleF argument in any subclasses that you register with UICollectionView. This is required because the classes are actually allocated by the Objective-C runtime, and you must initialize them. The following example shows the expected constructor that you should provide:

C# Example

public class AnimalCell : UICollectionViewCell
{
[Export ("initWithFrame:")]
  public AnimalCell (RectangleF frame) : base (frame) {}
}

The overridden methods UICollectionViewDataSource.GetCell and UICollectionViewSource.GetViewForSupplementaryElement show the re-assignment code. The NSIndexPath that is passed as the indexPath argument contains the NSIndexPath.Section and NSIndexPath.Item integers that allow the application developer to locate a specific data item and appropriately assign the cell's relevant visual elements. (Application developers familiar with UITableView will note that NSIndexPath.Item and NSIndexPath.Row are the same value.)

Since these methods, particularly the UICollectionViewDataSource.GetCell method, are called many times during scrolling, the application developer should avoid unnecessary processing during these calls.

C# Example

public class AnimalCell : UICollectionViewCell
{
  private static NSString classId = new NSString ("AnimalCell");
  public static NSString ClassId { get { return classId; } }

[Export ("initWithFrame:")]
  public AnimalCell (RectangleF frame) : base (frame) {}

//..etc...
}


public class SimpleCollectionViewController : UICollectionViewController
{
  public override void ViewDidLoad ()
  {
    Base.ViewDidLoad ();

    var cv = CollectionView;

    cv.RegisterClassForCell (typeof(AnimalCell), AnimalCell.ClassId);
    cv.RegisterClassForSupplementaryView (typeof(HeaderView), UICollectionElementKindSection.Header, HeaderView.ClassId);
    cv.CollectionViewLayout.RegisterClassForDecorationView (typeof(DecorationView), DecorationView.ClassId);
  }

  public override UICollectionViewCell GetCell (UICollectionView collectionView, Foundation.NSIndexPath indexPath)
  {
    var animalCell = (AnimalCell)collectionView.DequeueReusableCell (AnimalCell.ClassId, indexPath);
    var animal = animals [indexPath.Section * (animals.Count / SectionCount) + indexPath.Item];

    animalCell.Image = animal.Image;

    return animalCell;
  }


  public override UICollectionReusableView GetViewForSupplementaryElement (UICollectionView collectionView, NSString elementKind, NSIndexPath indexPath)
  {
    var headerView = (HeaderView)collectionView.DequeueReusableSupplementaryView (elementKind, HeaderView.ClassId, indexPath);
    headerView.Text = "Supplementary View Section " + indexPath.Section.ToString ();
    return headerView;
  }
  //...etc...
}

Rather than registering program classes, application developers may choose to register nibs defined with XCode's Interface Builder. The relevant methods are shown in the following table.

RoleClass Registration MethodNib Registration Method
CellUICollectionView.RegisterClassForCellUICollectionView.RegisterNibForCell
Supplementary ViewUICollectionView.RegisterClassForSupplementaryViewUICollectionView.RegisterNibForSupplementaryView
Decoration ViewUICollectionViewLayout.RegisterClassForDecorationViewUICollectionViewLayout.RegisterNibForDecorationView

Handling events

To handle events associated with a UICollectionView, the application developer may subtype UICollectionViewDelegate and assign an instance to the UICollectionView.Delegate property.

UICollectionView is a subtype of UIScrollView and UIScrollViewDelegate contains many of the same methods as UIScrollViewDelegate but is not a subtype of that class.

Selecting and highlighting in a UICollectionView follows this sequence:

User ActionUICollectionViewDelegate MethodsUICollectionViewCell Properties
Nothing touchedHighlighted == false; Selected == false
Finger down in cellUICollectionViewDelegate.ShouldHighlightItem is called. If it returns false, processing stops.
UICollectionViewDelegate.ItemHighlighted is called. Highlighted == true; Selected == false
Finger upUICollectionViewDelegate.ShouldSelectItem is called. If it returns false, processing stops.
UICollectionViewDelegate.ItemSelected is called. UICollectionViewDelegate.ItemUnhighlighted is called. Highlighted == false; Selected == true

Deselecting a UICollectionViewCell follows a similar sequence:

User ActionUICollectionViewDelegate MethodsUICollectionViewCell Properties
Nothing touched while some UICollectionViewCell is highlighted.Highlighted == false; Selected == true
Finger taps cell (Deselect gesture)UICollectionViewDelegate.ShouldDeselectItem is called. If it returns false, processing stops.
UICollectionViewDelegate.ItemDeselected is called. Highlighted == false; Selected == false

Related content

Requirements

Namespace: UIKit
Assembly: Xamarin.iOS (in Xamarin.iOS.dll)
Assembly Versions: 0.0.0.0

The members of UIKit.UICollectionView are listed below.

See Also: UIScrollView

Public Constructors

A constructor that initializes the object from the data stored in the unarchiver object.
Instantiates a new UICollectionView with the specified layout.

Protected Constructors

Constructor to call on derived classes to skip initialization and merely allocate the object.
A constructor used when creating managed representations of unmanaged objects; Called by the runtime.

Public Properties

AllowsMultipleSelectionBoolean. Specifies whether more than one UICollectionViewCell can be selected at a time.
AllowsSelectionBoolean. Specifies whether an application user can select a UICollectionViewCell by tapping.
[read-only]
static
AppearanceUICollectionView+UICollectionViewAppearance. Strongly-typed property that returns the UIAppearance class for this class.
BackgroundViewUIView. A UIView that lies behind all other content and is automatically sized to fill the entire bounds.
[read-only]
override
ClassHandleIntPtr. The handle for this class.
CollectionViewLayoutUICollectionViewLayout. The UICollectionViewLayout that will lay out this UICollectionView's elements.
DataSourceIUICollectionViewDataSource. The UICollectionViewDataSource responsible for populating this UICollectionView.
DelegateIUICollectionViewDelegate. An instance of the UIKit.UICollectionViewDelegate model class which acts as the class delegate.
[read-only]
IndexPathsForVisibleItemsNSIndexPath[]. Returns the NSIndexPaths of all visible items.
PrefetchDataSourceIUICollectionViewDataSourcePrefetching. Gets or sets the prefetch-capable source for this collection view.
PrefetchingEnabledBoolean. Gets or sets whether prefecting is enabled. If true, UICollectionView.PrefetchDataSource must be set.
RemembersLastFocusedIndexPathBoolean. Whether focus should return to the last-focused index path after it leaves and then re-enters the UICollectionView.
SourceUICollectionViewSource. An optional property that can substitute for the UICollectionView.DataSource and UICollectionView.Delegate properties
[read-only]
VisibleCellsUICollectionViewCell[]. An array of the currently-visible UICollectionViewCell.
WeakDataSourceNSObject. The data source that provides data for this UICollectionView.
WeakDelegateNSObject. An object that can respond to the delegate protocol for this type

Public Methods

static
AppearanceWhenContainedIn(params Type[]) : UICollectionView+UICollectionViewAppearance
Returns a strongly typed UIAppearance for instances of this class when the view is hosted in the specified hierarchy.
BeginInteractiveMovementForItem(NSIndexPath) : Boolean
Developers call this method to have the cell at indexPath begin interactive movement.
CancelInteractiveMovement()
Developers call this method to cancel interactive movement and have the cell return to its previous position.
CancelInteractiveTransition()
Cancels an interactive transition and returns to its original layout object.
CellForItem(NSIndexPath) : UICollectionViewCell
Returns the UICollectionViewCell at the specified NSIndexPath.
DeleteItems(NSIndexPath[])
Deletes one or more items from the UICollectionView.
DeleteSections(NSIndexSet)
Deletes one or more sections from the UICollectionView.
DequeueReusableCell(NSString, NSIndexPath) : UICollectionReusableView
Returns a new or reused UICollectionReusableView.
DequeueReusableCell(String, NSIndexPath) : UICollectionReusableView
Returns a new or reused UICollectionReusableView.
DequeueReusableSupplementaryView(NSString, NSString, NSIndexPath) : UICollectionReusableView
Returns a newly-allocated or reused supplementary UICollectionReusableView.
DequeueReusableSupplementaryView(NSString, String, NSIndexPath) : UICollectionReusableView
Returns a UICollectionReusableView.
DequeueReusableSupplementaryView(UICollectionElementKindSection, NSString, NSIndexPath) : NSObject
Returns a newly-allocated or reused supplementary UICollectionReusableView.
DequeueReusableSupplementaryView(UICollectionElementKindSection, String, NSIndexPath) : UICollectionReusableView
Returns a UICollectionReusableView.
DeselectItem(NSIndexPath, Boolean)
Deselects the UICollectionViewCell at the specified NSIndexPath.
EncodeTo(NSCoder)
Encodes the state of the object on the provided encoder
EndInteractiveMovement()
Developers call this method to finish interactive movement.
FinishInteractiveTransition()
Finishes an interactive transition and installs the intended target layout.
static
GetAppearance(UITraitCollection) : UICollectionView+UICollectionViewAppearance
Obtains the appearance proxy UICollectionViewAppearance for the subclass of UICollectionView.
static
GetAppearance(UITraitCollection, params Type[]) : UICollectionView+UICollectionViewAppearance
Obtains the appearance proxy UICollectionViewAppearance for the subclass of UICollectionView.
static
GetAppearance<T>() : UICollectionView+UICollectionViewAppearance
Obtains the appearance proxy UICollectionViewAppearance for the subclass of UICollectionView.
static
GetAppearance<T>(UITraitCollection) : UICollectionView+UICollectionViewAppearance
Obtains the appearance proxy UICollectionViewAppearance for the subclass of UICollectionView.
static
GetAppearance<T>(UITraitCollection, params Type[]) : UICollectionView+UICollectionViewAppearance
Obtains the appearance proxy UICollectionViewAppearance for the subclass of UICollectionView that has the specified trait collection when the view is hosted in the specified hierarchy.
GetIndexPathsForSelectedItems() : NSIndexPath[]
Returns an array of NSIndexPaths indicating which cells are currently selected.
GetIndexPathsForVisibleSupplementaryElements(NSString) : NSIndexPath[]
Returns the index path(s) of visible supplementary views of the specified elementKind.
GetLayoutAttributesForItem(NSIndexPath) : UICollectionViewLayoutAttributes
Returns the layout information for the specified UICollectionViewCell.
GetLayoutAttributesForSupplementaryElement(NSString, NSIndexPath) : UICollectionViewLayoutAttributes
Returns the layout information for the specified supplementary view.
GetSupplementaryView(NSString, NSIndexPath) : UICollectionReusableView
Rerieves the supplementary view at the specified indexPath.
GetVisibleSupplementaryViews(NSString) : UICollectionReusableView[]
Retrieves the array of visible header or footer supplementary views.
IndexPathForCell(UICollectionViewCell) : NSIndexPath
Returns the NSIndexPath for the cell.
IndexPathForItemAtPoint(CGPoint) : NSIndexPath
Returns the NSIndexPath for the point.
InsertItems(NSIndexPath[])
Creates new cells in the UICollectionView, animating as necessary.
InsertSections(NSIndexSet)
Creates new sections in the UICollectionView, animating as necessary.
MoveItem(NSIndexPath, NSIndexPath)
Moves an element from one location to another within the UICollectionView, animating as necssary.
MoveSection(nint, nint)
Moves a section from one location to another within the UICollectionView, animating as necessary.
NumberOfItemsInSection(nint) : nint
Returns the number of items in the specified section.
NumberOfSections() : nint
Returns the number of sections in the UICollectionView.
PerformBatchUpdates(Action, UICompletionHandler)
Applies and simultaneously animates multiple manipulations of the UICollectionView.
PerformBatchUpdatesAsync(Action) : System.Threading.Tasks.Task<bool>
Applies and simultaneously animates multiple manipulations of the group.
RegisterClassForCell(Type, NSString)
Specifies the type to be used to populate cells.
RegisterClassForCell(Type, String)
Specifies the type to be used to populate cells.
RegisterClassForSupplementaryView(Type, NSString, NSString)
Specifies the type to be used to populate supplementary views.
RegisterClassForSupplementaryView(Type, NSString, String)
Specifies the type to be used to populate supplementary views.
RegisterClassForSupplementaryView(Type, UICollectionElementKindSection, NSString)
Specifies the type to be used to populate supplementary views.
RegisterClassForSupplementaryView(Type, UICollectionElementKindSection, String)
Specifies the type to be used to populate supplementary views.
RegisterNibForCell(UINib, NSString)
Specifies the type to be used to populate cells.
RegisterNibForCell(UINib, String)
Registers the Nib file that will be used for cell UI.
RegisterNibForSupplementaryView(UINib, NSString, NSString)
Specifies the type to be used to populate supplementary views.
RegisterNibForSupplementaryView(UINib, UICollectionElementKindSection, NSString)
Specifies the nib to be used for populating the supplementary view.
RegisterNibForSupplementaryView(UINib, UICollectionElementKindSection, String)
Registers the Nib file that will be used for UI in supplementary views.
ReloadData()
Reloads all of the data for the UICollectionView.
ReloadItems(NSIndexPath[])
Reloads the data for the specified elements.
ReloadSections(NSIndexSet)
Reloads the data in the specified sections of the UICollectionView.
ScrollToItem(NSIndexPath, UICollectionViewScrollPosition, Boolean)
Scrollls the UICollectionView so that the desired element is visible.
SelectItem(NSIndexPath, Boolean, UICollectionViewScrollPosition)
Selects a UICollectionViewCell and optionally scrolls to make it visible.
SetCollectionViewLayout(UICollectionViewLayout, Boolean)
Changes the UICollectionViewLayout used by the UICollectionView.
SetCollectionViewLayout(UICollectionViewLayout, Boolean, UICompletionHandler)
Sets the layout used by this UICollectionView.
SetCollectionViewLayoutAsync(UICollectionViewLayout, Boolean) : System.Threading.Tasks.Task<bool>
Sets the layout used by this .
StartInteractiveTransition(UICollectionViewLayout, UICollectionViewLayoutInteractiveTransitionCompletion) : UICollectionViewTransitionLayout
Changes the UICollectionView's layout using an interactive transition.
StartInteractiveTransitionAsync(UICollectionViewLayout) : System.Threading.Tasks.Task<UICollectionViewTransitionResult>
Changes the UICollectionView's layout using an interactive transition.
StartInteractiveTransitionAsync(UICollectionViewLayout, out UICollectionViewTransitionLayout) : System.Threading.Tasks.Task<UICollectionViewTransitionResult>
Asynchronously starts an interactive transition to the new layout, with a reference to the result.
UpdateInteractiveMovement(CGPoint)
Developers periodically call this method to set the position of the moving cell.

Protected Methods

override
Dispose(Boolean)
Releases the resources used by the UICollectionView object.
RegisterClassForSupplementaryView(IntPtr, NSString, NSString)
Specifies the type to be used to populate supplementary views.