Keep cellView cell position after clicking on the zoom button

I have a collectionView that I can scale on compression.

It works as follows:

I added UIPinchGestureRecognizer to collectionView, when a pinch occurs, I have an invalid layout that forces collectionView to request a delegate for a new size.

It works well.

The problem that I cannot fix is ​​that during the pinch I want to keep my cell in the same position. Just below the indicator in the middle of the screen. (see screenshot).

I thought of storing the current scrollView offset when the pinch starts, when the cell is redrawn with a new size, I calculate the difference in width and add or subtract for contentOffset.

I have a contentInset to scroll the first cell in the middle in the View collection.

Here is my code:

@objc func handlePinchGesture(gesture: UIPinchGestureRecognizer) {

if (gesture.state == .Began) {
    scaleStart = metrics.scale // remember current scale
    widthStart = collectionView.visibleCells()\[0\].bounds.width // get size of a cell to calulate a difference when scale will change
    originalContentOffset = collectionView.contentOffset.x // remember original content offset
}
else if (gesture.state == .Changed) {

    let newScale = metrics.normalizeScale(scaleStart * gesture.scale) // normalize scale. give 0.5, 1, 1.5, 2

    metrics.scale = newScale // global struct

    //let ZoomIn = (newScale > scaleStart)

    collectionView.collectionViewLayout.invalidateLayout() // invalidate layout in order to redisplay cell with updated scale

    let scaleRatio = newScale / self.scaleStart
    var newContentOffset = CGFloat(0)

    let widthDiff: CGFloat = (scaleRatio * self.widthStart) - self.widthStart

    newContentOffset = originalContentOffset + widthDiff

    self.collectionView.setContentOffset(CGPointMake(newContentOffset ,0), animated: false)
    }
}

It just doesn't work ...

Do you have an idea?

Thanks so much for your input.

Here is a screenshot of what I have and I want with the correct offsets. But I can’t find the right way to calculate the content offset after the hard-press.

screenshot

Thierry

+4
source share

All Articles