tezvyn:

Allow simultaneous pan and pinch gestures

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Simultaneous gesture recognition via the delegate.

OUTLINE

Attach pan and pinch recognizers, set yourself as delegate, return true from shouldRecognizeSimultaneouslyWith, apply translation to center and scale to transform.

WHAT THIS TESTS This checks whether you know that, by default, only one gesture recognizer wins a touch sequence, and how the delegate opts into simultaneous recognition, plus the bookkeeping that keeps transforms stable.

A GOOD ANSWER COVERS Create a UIPanGestureRecognizer and a UIPinchGestureRecognizer, add both to the same view, and enable userInteractionEnabled. Set an object as the delegate of both recognizers. Implement the UIGestureRecognizerDelegate method gestureRecognizer(_:shouldRecognizeSimultaneouslyWith:) and return true, which tells UIKit the pan and pinch may both be active for the same touches. In the pan handler, read translation(in:) and apply it, typically by updating the view's center, then call setTranslation(.zero, in:) so the next callback reports a delta rather than an accumulating total. In the pinch handler, multiply the view's transform by a scale of the recognizer's scale, then reset gesture.scale to 1 to avoid compounding.

COMMON WRONG ANSWERS Expecting both gestures to fire simultaneously without implementing the delegate method, so only one ever activates. Applying the cumulative translation or scale every callback, causing the view to jump or grow exponentially. Mixing center-based panning with a scale transform without realizing transforms make frame unreliable.

LIKELY FOLLOW-UPS How to handle anchor point so pinch scales around the touch midpoint. Why you might prefer applying both as a single combined CGAffineTransform when rotation is added too. The difference between this delegate method and require(toFail:).

ONE CONCRETE EXAMPLE You attach pan and pinch to an image view and set self as delegate. shouldRecognizeSimultaneouslyWith returns true. In handlePan you do let t = pan.translation(in: view.superview); view.center = CGPoint(x: view.center.x + t.x, y: view.center.y + t.y); pan.setTranslation(.zero, in: view.superview). In handlePinch you do view.transform = view.transform.scaledBy(x: pinch.scale, y: pinch.scale); pinch.scale = 1. Now the user can drag and pinch the image together smoothly.

Read the original → developer.apple.com

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.