Creating Collection View Cells from a Xib

I’ve had the question of how to create a collection view cell using a xib file come up a few times, so I figured I would put together a quick example to show how to do it. In this case, I just created a collection view with 100 cells each containing a label:

cv_xib_cells

Basically, you need to register the cell using the CollectionView.RegisterNibForCell method like this:

CollectionView.RegisterNibForCell (UINib.FromName ("CVCell", NSBundle.MainBundle),
  cellId);

There is a template file in Xamarin Studio you can use to create a collection view cell. This will create a xib to design the cell in, along with a class that is wired up to the xib. The template adds a bit of additional code but all you really need is the constructor that takes an IntPtr, as the class will be created by iOS via the call to DequeueReusableCell.

For example, here’s the code for the cell I’m using in this simple example:

public partial class CVCell : UICollectionViewCell
{
    public string Text {
        set{
            Label.Text = value;
        }
    }

    public CVCell (IntPtr handle) : base (handle)
    {
    }
}

The Text property simply sets the text on a UILabel that is added in Interface Builder.

The code to create the cell in the UIViewController is just like when you create the cell entirely in code:

public override UICollectionViewCell GetCell (UICollectionView collectionView, NSIndexPath indexPath)
{
    var cell = (CVCell)collectionView.DequeueReusableCell (cellId, indexPath);

    cell.Text = indexPath.Row.ToString ();

    return cell;
}

The project is available in my github repo here.

3 thoughts on “Creating Collection View Cells from a Xib

  1. Hi there,

    Quick question…how did you get your label to be associated with the UICollectionViewCell with the auto-generated code?

    Every time I drag it on, it assigns it to the main view controller in the code-behind, not the cell (though visually it looks like it’s attached to the cell in the StoryBoard)

    Thanks

    • My apologies – I was referring to using the Storyboard and the UICollectionViewCell component within Xamarin and not the XIB (the former is still an issue – assuming Xamarin bug at this stage as they had the same issue with the TableCollection vie but fixed it).

      However, your post did make me research using XIB templates directly (I’m one week in into my learning of Xamarin and iOS)…so thanks. Noticed your contribution also to the Xamarin forum – good work 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s