我很难实现NSUndoManager,我尝试阅读它上面的苹果文档,但我无法弄明白。这是我到目前为止所尝试的。我创建了一个通过连接数组中的两个点来绘制线条的应用程序,我通过删除最后一个对象实现了一个撤销方法,但是无法弄清楚如何实现重做,我偶然发现了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];
}
我没有错误,但在运行时,当我点击按钮时,没有任何反应。我对NSUndoManager不了解的是事情的发展方向,"对象"是。我没有声明我需要声明的内容。
谢谢,
答案 0 :(得分:0)
当您绘制一条线时,touchesMoved方法将多次调用,因此如果您在touchesMoved方法中注册撤消操作,则需要对它们进行分组:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.undoManager beginUndoGrouping];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.undoManager endUndoGrouping];
}
这里是example。
答案 1 :(得分:0)