实现NSUndoManager
我很难实现NSUndoManager,我尝试阅读它的苹果文档,但我无法弄清楚。 这是我迄今为止所尝试过的。 我已经创build了一个应用程序,通过连接数组中的两点来绘制线,我通过删除最后一个对象实现了一个撤消方法,但不知道如何实现重做,我偶然发现NSUndoManager,并开始阅读它的文档,但我没有知道如何将其应用于我的问题。 下面是我现在的代码
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { NSUInteger taps = [[touches anyObject]tapCount]; if(taps == 2) { [self setNeedsDisplay]; } else { if([self.pointsArray count] == 0) { self.pointsArray = [[NSMutableArray alloc]init]; UITouch *t = [touches anyObject]; CGPoint startLoc = [t locationInView:self]; [self.pointsArray addObject:[NSValue valueWithCGPoint:startLoc]]; } } } -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *t = [touches anyObject]; CGPoint currentLoc = [t locationInView:self]; [self.pointsArray addObject:[NSValue valueWithCGPoint:currentLoc]]; [self setNeedsDisplay]; } #pragma mark - Undo/Redo Methods -(void)undo:(id) object { [[undoManager prepareWithInvocationTarget:self]redo:object]; [undoManager setActionName:@"undoLineSegment"]; [self.pointsArray removeLastObject]; } -(void)redo:(id)object { [self.pointsArray addObject:object]; [[undoManager prepareWithInvocationTarget:self]undo:object]; [undoManager setActionName:@"RedoUndoneLineSegment"]; } - (IBAction)undoButton:(UIButton *)sender { [self.undoManager undo]; [self setNeedsDisplay]; } - (IBAction)redoButton:(UIButton *)sender { [self.undoManager redo]; [self setNeedsDisplay]; }
我没有得到任何的错误,但在运行时,当我点击button,没有任何反应。 我对NSUndoManager不了解的是事情的发展,“对象”是什么。 我没有宣布我需要申报的东西吗?
谢谢,
touchesMoved方法在绘制线条时会多次调用,所以如果在touchesMoved方法中注册了撤消操作,则需要对它们进行分组:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { [self.undoManager beginUndoGrouping]; } - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { [self.undoManager endUndoGrouping]; }
这里是一个例子 。