首先,請閱讀「Using Undo on iPhone」。確保你已經在你的響應者鏈中設置了undoManager
屬性(可能在你的視圖控制器中)。
我們只想在手勢結束時推送撤消操作。但是當我們推動撤消動作時,我們需要知道手勢開始時視圖的變換。創建一個實例變量來保存原來的變換:
@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;
}
}
但是,如果用戶將其旋轉100次,則撤銷重做功能將無法正常工作。用戶將不得不按100次撤消將其旋轉到原始位置。所以我只想爲uigesturerecognisersendeded設置撤消管理器。怎麼做。 – 2012-02-06 05:29:14
我改變了我的答案。 – 2012-02-06 05:59:37
非常感謝您的幫助。 – 2012-02-06 06:21:31