Zoom a Collection View

PDF for offline use
Sample Code:
Related SDKs:

Let us know how you feel about this

Translation Quality


0/250

This recipe shows how to use a gesture recognizer to allow the user to zoom in a Collection View.

Recipe

To allow a user to zoom in a Collection View, you first need to add a gesture recognizer to your View:

public override void ViewDidLoad ()
    {
        base.ViewDidLoad ();

        UIPinchGestureRecognizer pinch = new UIPinchGestureRecognizer (handlePinchGesture);
        this.CollectionView.AddGestureRecognizer (pinch);
    }

Then add a handler method to respond to the gesture:

public void handlePinchGesture (UIPinchGestureRecognizer gesture)
{
    if (gesture.State == UIGestureRecognizerState.Began)
    {
        scaleStart = this.scale;
    }
    else if (gesture.State == UIGestureRecognizerState.Changed)
    {
        this.scale = scaleStart * gesture.Scale;

        this.CollectionView.CollectionViewLayout.InvalidateLayout ();
    }
}

Finally, in the Collection View's delegate, you will need to override the GetSizeForItem() method to apply the zoom's scale factor to the size of each item:

public override System.Drawing.CGSize GetSizeForItem (UICollectionView collectionView, UICollectionViewLayout layout, NSIndexPath indexPath)
    {
        return new System.Drawing.CGSize (50 * parent.scale, 50 * parent.scale);
    }

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.