NSUndoManager使用旋转手势来撤销UIImage旋转

如何使用NSUndoManager旋转UIImageView使用旋转手势? 这是我的代码轮换。

 - (void)handleRotate:(UIRotationGestureRecognizer *)recognizer { if (recognizer.state == UIGestureRecognizerStateBegan) { prevRotation = 0.0; } float thisRotate = recognizer.rotation - prevRotation; prevRotation = recognizer.rotation; recognizer.view.transform = CGAffineTransformRotate(recognizer.view.transform, thisRotate); CGPoint lastpoint = point; } 

首先阅读“在iPhone上使用撤销” 。 确保你已经在响应者链中的某个地方设置了undoManager属性(可能在你的视图控制器中)。

我们只想在手势结束时推送撤消动作。 但是当我们推动撤消动作时,我们需要知道手势开始时视图的变换。 创build一个实例variables来保存原始的变换:

 @implementation YourViewController { CGAffineTransform _originalImageViewTransform; } 

接下来,我们需要一个方法来推送撤销操作并设置视图的变换:

 - (void)setTransform:(CGAffineTransform)newTransform ofView:(UIView *)view undoTransform:(CGAffineTransform)undoTransform { // If I'm called because the gesture ended, this pushes an undo action. // If I'm called because the user requested an undo, this pushes a redo action. [[self.undoManager prepareWithInvocationTarget:self] setTransform:undoTransform ofView:view undoTransform:newTransform]; // Now actually set the transform. view.transform = newTransform; } 

您的handleRotate:方法需要检测手势的状态并采取适当的行动。

 - (void)handleRotate:(UIRotationGestureRecognizer *)recognizer { UIView *view = recognizer.view; UIGestureRecognizerState state = recognizer.state; if (state == UIGestureRecognizerStateCancelled) { view.transform = _originalImageViewTransform; return; } if (state == UIGestureRecognizerStateBegan) { _originalImageViewTransform = view.transform; } CGAffineTransform transform = view.transform; transform = CGAffineTransformRotate(transform, recognizer.rotation); recognizer.rotation = 0; // This line means we don't need prevRotation if (state == UIGestureRecognizerStateEnded) { [[ The gesture ended, so push an undo action before setting the transform. [self setTransform:transform ofView:view undoTransform:_originalImageViewTransform]; } else { // The gesture changed but didn't end, so don't push an undo action. view.transform = transform; } }