简体   繁体   中英

What is a good way to reset a UIPanGestureRecognizer's view to its original frame once the pan gesture is done?

Say you have a pinch gesture recognizer and pan gesture recognizer on my image view:

@IBAction func pinchPiece(_ pinchGestureRecognizer: UIPinchGestureRecognizer) {
    guard pinchGestureRecognizer.state == .began || pinchGestureRecognizer.state == .changed,
          let piece = pinchGestureRecognizer.view else {
            // After pinch releases, zoom back out.
            if pinchGestureRecognizer.state == .ended {
              UIView.animate(withDuration: 0.3, animations: {
                pinchGestureRecognizer.view?.transform = CGAffineTransform.identity
              })
            }
            return
    }
    adjustAnchor(for: pinchGestureRecognizer)
    
    let scale = pinchGestureRecognizer.scale
    piece.transform = piece.transform.scaledBy(x: scale, y: scale)
    pinchGestureRecognizer.scale = 1 // Clear scale so that it is the right delta next time.
}

@IBAction func panPiece(_ panGestureRecognizer: UIPanGestureRecognizer) {
    guard panGestureRecognizer.state == .began || panGestureRecognizer.state == .changed,
          let piece = panGestureRecognizer.view else {
        return
    }
    let translation = panGestureRecognizer.translation(in: piece.superview)
    piece.center = CGPoint(x: piece.center.x + translation.x, y: piece.center.y + translation.y)
    panGestureRecognizer.setTranslation(.zero, in: piece.superview)
}

public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer,
                            shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    true
}

The pinch gesture's view resets to its original state after the gesture is done, which occurs in its else clause. What would be a good way to do the same for the pan gesture recognizer? Ideally I'd like the gesture recognizers to be in an extension of UIImageView , which would also mean that I can't add a store property to the extension for tracking the initial state of the image view.

Since UIImageView is Hashable , you can store a STATIC dictionary, using the image view itself as a key and some struct as the value, with whatever data you need to "remember" in order to restore the view to its original state. Note that static properties can be stored from extensions (as opposed to stored properties).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM