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.

About these ads

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s