View blocked from moving after being rotated

72 Views Asked by At

I implemented touchesMoved method for moving my view around and RotationGestureRecognizer to rotate it. It works normal, I can move and rotate my view. The problem is that the view after being rotated cannot be moved anymore. It pins itself to center and doesn't go anywhere. Here are the gifs as a visual description of the problem:

View is moved around its superview

View won't move after rotation

touchesMoved methode:

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let sv = superview, let touch = touches.first else { return }
    
    let parentFrame = sv.bounds
    
    let location = touch.location(in: self)
    let previousLocation = touch.previousLocation(in: self)
    
    var newFrame = self.frame.offsetBy(dx: location.x - previousLocation.x, dy: location.y - previousLocation.y)
    
    newFrame.origin.x = max(newFrame.origin.x, 0.0)
    newFrame.origin.x = min(newFrame.origin.x, parentFrame.size.width - newFrame.size.width)
    newFrame.origin.y = max(newFrame.origin.y, 0.0)
    newFrame.origin.y = min(newFrame.origin.y, parentFrame.size.height - newFrame.size.height)
    
    self.frame = newFrame
}

RotationGestureRecognizer method:

@objc func rotationGestureHandler(recognizer:UIRotationGestureRecognizer) {
    if let view = recognizer.view {
        view.transform = view.transform.rotated(by: recognizer.rotation)
        print(view.frame)
        recognizer.rotation = 0
    }
}

Any ideas why this can happen? Thanks to everybody in advance

1

There are 1 best solutions below

0
Neklas On
yourGestureRecognizer.cancelsTouchesInView = true (this is default value)

Because your Rotate Gesture "cancel" your touch in this view, so the touchMoved isn't triggered.

When this property is true (the default) and the gesture recognizer recognizes its gesture, the touches of that gesture that are pending aren’t delivered to the view and previously delivered touches are canceled through a touchesCancelled(_:with:) message sent to the view. If a gesture recognizer doesn’t recognize its gesture or if the value of this property is false, the view receives all touches in the multi-touch sequence.

Check this here: https://developer.apple.com/documentation/uikit/uigesturerecognizer/1624218-cancelstouchesinview