Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pinch gesture to expand a UICollectionView Cell

An application I'm working on requires a layout very similar to that of the Photos app on iPad. There's a grid of UIViews and the user should be able to pinch into a single one, and as they're pinching in, watch that view grow in size until it's full screen.

So far, I have set up a UICollectionViewController and a custom collection view cell. I added the pinch gesture recognizer to the custom cell. When the user pinches in, the cell grows in size.

The issue I am now having is that the cell isn't layering on top of all other cells as it expands. Rather, it is hiding under the cells loaded after it.

I was thinking that the solution may be that when the collection view controller recognizes the pinch gesture, it could hide the cell being pinched on. Then, create a new UIView that is a copy of the collection view cell, with the bounds equivalent to where the cell was placed. Then, this view can be the one that can be pinched, rotated, and panned. As soon as the user ends the gesture, the view would just animate back to the original cell position and then be set to nil.

However, I'm not sure if this is the optimal solution and maybe there's some easy way to ensure a certain cell is layered on top of all other cells in the collection view.

The code for a snippet of my current implementation of how I'm scaling the cell is shown below. This is the one that creates the issue of the cell hiding under later cells as it expands.

 @objc func scalePiece(_ gestureRecognizer : UIPinchGestureRecognizer) {
    guard gestureRecognizer.view != nil else { return 

    if gestureRecognizer.state == .began || 
       gestureRecognizer.state == .changed {

        gestureRecognizer.view?.transform = (gestureRecognizer.view?.transform.scaledBy(x: gestureRecognizer.scale, y: gestureRecognizer.scale))!

        gestureRecognizer.scale = 1.0

    }
}
like image 945
P. B. Avatar asked Nov 06 '22 21:11

P. B.


1 Answers

One dirt-simple possibility to remedy the cell being behind others is to invoke bringSubviewToFront(_:) on the collection view, passing the cell.

Caveat however, I'm not sure that this is optimal: since you don't really own the cells/the collection view's hierarchy, generally speaking you shouldn't touch the subviews directly like this.

A closely-related possibility -- not as simple, but probably much more robust and thus preferable -- is to customize the layout. Since the collection view's UICollectionViewLayout object can specify the zIndex of a particular cell, you could reload the cell when the pinch gesture begins and update the Z index for just that cell.

like image 177
jscs Avatar answered Nov 14 '22 22:11

jscs