Skip to content

UICollectionViewCell ​

UICollectionViewCell represents a cell: the on-screen view for one item in a UICollectionView.

Cells can't be created with new; they can only be obtained in the data source's cellProvider with dequeueReusableCellWithReuseIdentifier(). Cells are reused: after an item scrolls off screen, its cell is taken to display another item. So cellProvider must set all of the cell's content every time and can't assume the cell is new.

The content shown in a cell comes from two sources: the primary text, secondary text, and image given by contentConfiguration, and subviews the app adds to contentView itself.

List layouts use its subclass UICollectionViewListCell, which adds a method that provides a default content style.

Inheritance: EventTarget → NSObject → UIResponder → UIView → UICollectionReusableView → UICollectionViewCell

Constructor ​

Can't be created with new; new UICollectionViewCell() throws TypeError. Register it first with registerClass(), then obtain it in cellProvider.

Instance properties ​

Also inherits properties from UICollectionReusableView and UIView, such as reuseIdentifier.

PropertyDescription
contentView read-onlyWhere you put your own subviews
contentConfigurationThe cell's content: primary text, secondary text, image
isSelectedWhether this item is selected
isHighlightedWhether a finger is currently pressing this item

Examples ​

Putting your own label in a cell ​

Cells are reused, so create subviews only the first time a cell is used, and afterward change only the content.

js
/** @type {WeakMap<UICollectionViewCell, UILabel>} */
const priceLabels = new WeakMap();

/** @param {UICollectionViewCell} cell */
function priceLabelOf(cell) {
  let label = priceLabels.get(cell);
  if (label === undefined) {
    label = new UILabel();
    label.translatesAutoresizingMaskIntoConstraints = false;
    cell.contentView.addSubview(label);
    NSLayoutConstraint.activateConstraints([
      label.trailingAnchor.constraintEqualToAnchor(cell.contentView.trailingAnchor, { constant: -16 }),
      label.centerYAnchor.constraintEqualToAnchor(cell.contentView.centerYAnchor),
    ]);
    priceLabels.set(cell, label);
  }
  return label;
}

Effect: after getting a cell in cellProvider, call priceLabelOf(cell).text = '¥ 128', and each row gets a price on its right side. How it looks on screen is not verified in the simulator; verified by testing: subviews can be added to contentView, and the same cell obtained again is the same JS object.

Corresponding iOS API ​

ObjCJS
cell.contentViewcell.contentView
cell.contentConfiguration = contentcell.contentConfiguration = content
cell.selectedcell.isSelected
cell.highlightedcell.isHighlighted

See also ​