问题
I have a label on the UIImageView
as below.
The label is draggable, pan-able and pinch-able. However I can only do one gesture at a time. For example, I want to drag the label while I'm pinching it like in texts on images in Snapchat and Whatsapp. My functions are as below. As I searched, I think I should create a custom gesture recognizer but I don't know how. Is there any way I can do it without creating a custom recognizer?
I got help from this post while doing this: Snapchat-like text on image
func handlePan(recognizer: UIPanGestureRecognizer) {
var translation = recognizer.translation(in: allview)
translation.x = max(translation.x, imageview.frame.minX - mylabel.frame.minX)
translation.x = min(translation.x, imageview.frame.maxX - mylabel.frame.maxX)
translation.y = max(translation.y, imageview.frame.minY - mylabel.frame.minY)
translation.y = min(translation.y, imageview.frame.maxY - mylabel.frame.maxY)
if let view = recognizer.view {
view.center = CGPoint(x:view.center.x + translation.x,
y:view.center.y + translation.y)
}
recognizer.setTranslation(CGPoint.zero , in: view)
}
func handlePinch(recognizer: UIPinchGestureRecognizer) {
if let view = recognizer.view as? UILabel {
let pinchScale: CGFloat = recognizer.scale
view.transform = view.transform.scaledBy(x: pinchScale, y: pinchScale)
recognizer.scale = 1.0
}
}
func handleRotate(recognizer: UIRotationGestureRecognizer) {
if let view = recognizer.view as? UILabel {
let rotation: CGFloat = recognizer.rotation
view.transform = view.transform.rotated(by: rotation)
recognizer.rotation = 0.0
}
}
回答1:
I solved by adding "UIGestureRecognizerDelegate" to my ViewController. This allows using gestures at the same time. I'm sure creating custom gesture will work better but this also do the work. Add this three line of codes on viewDidLoad function
pinchRecognizer.delegate = self
panRecognizer.delegate = self
rotateRecognizer.delegate = self
Also do not forget to add functin for delegate which is;
func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
来源:https://stackoverflow.com/questions/40934454/pinch-drag-and-pan-at-the-same-time