How to register a click event on a CollectionViewCell, and handle that event.

JPHochbaumJPHochbaum USMember ✭✭✭
edited December 2016 in Xamarin.iOS

I am not finding any accurate or useful documentation on how to accomplish this. Anyone have examples they could share?


  • Mahesh.5770Mahesh.5770 USMember ✭✭

    Hi Jochnaum,

    I am assuming your using mvvm pattren, the following link will be helpful to you.

    Thank you.

  • JPHochbaumJPHochbaum USMember ✭✭✭

    That is not what I mean. I will drop some of my code to help explain. This is inside my CustomCollectionSource class which is being used to populate my cells with data. Supposedly from the little documentation that I have seen I am supposed to register a TouchUpINside event on the cell in here:

    ` public override UICollectionViewCell GetCell(UICollectionView collectionView, NSIndexPath indexPath)
    var cell = (CustomCollectionViewCell)collectionView.DequeueReusableCell(CustomCollectionViewCell.cellID, indexPath);

            if(indexPath.Row % 2 == 0 && this.isWhite)
                cell.ContentView.BackgroundColor = UIColor.White;
                cell.BackgroundColor = cell.ContentView.BackgroundColor;
                this.isWhite = false;
            if(indexPath.Row % 2 == 0 && this.isGray)
                cell.ContentView.BackgroundColor = UIColor.Gray;
                cell.BackgroundColor = cell.ContentView.BackgroundColor;
                this.isGray = false;
                this.isWhite = true;
            if(this.isWhite == false)
                this.isGray = true;
            return cell;

    But there are no events to register for the cell.(method or property, no event).

    The other thought I had was to register it in my ViewController after it all the cells are populated. But:
    1) I don't know how I can register an event on a cell when it is not populated in the ViewController class
    2) I am trying to mimic what I have in android with a listView, where I can register a click event on a listview item.

  • JPHochbaumJPHochbaum USMember ✭✭✭

    From what it seems the cells in a CollectionViewCell are a UIView and those don't seem to have the capability to register an event. Very weird. not sure how to work around this.

  • JPHochbaumJPHochbaum USMember ✭✭✭

    Also tried using GestureDetector, but my selected items array isn't null but has 0 elements.

    public override void ViewDidLoad() { UITapGestureRecognizer tap = new UITapGestureRecognizer(this.ItemTap); collectionView.AddGestureRecognizer(tap); }

    public void ItemTap() { this.selectedItems = this.collectionView.GetIndexPathsForSelectedItems(); if (this.selectedItems.Length > 0) { int row = this.selectedItems[0].Row; var x = 0; } }

Sign In or Register to comment.