难以实现NSUndoManager重做功能

时间:2011-11-23 21:46:26

标签: objective-c ios cocoa-touch nsundomanager

我正在尝试在我的iOS应用中实现NSUndoManager。我有撤消功能,但不是重做部分。我对iOS开发很新,这是我第一次使用NSUndoManager所以它可能是微不足道的。

我的应用程序是一个绘画/笔记记录应用程序,我有一个撤消/重做堆栈,其中包含最后十个UIImage(我不知道这是否是最有效的方法)。当用户对当前图像进行更改时,旧图像被压入堆栈,如果阵列已经有十个对象,则删除阵列中的第一个图像。我有一个int实例变量,用于跟踪数组中的对象并确保显示正确的图像。我的代码如下所示:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    if (oldImagesArrays.count >= 10) {
        [oldImagesArrays removeObjectAtIndex:0];
    }
    UIImage * currentImage = pageView.canvas.image;
    if (currentImage != nil) {
        [oldImagesArrays addObject:currentImage];
        undoRedoStackIndex = oldImagesArrays.count -1;
    }
    [...]
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {

    UIImage * currentImage = [oldImagesArrays lastObject];
    if (currentImage != pageView.canvas.image) {
        [undoManager registerUndoWithTarget:self selector:@selector(resetImage)  
        object:currentImage];
    }
}

// Gets called when the undo button is clicked
- (void)undoDrawing
{
    [undoManager undo];
    [undoManager registerUndoWithTarget:self 
                           selector:@selector(resetImage)
                             object:pageView.canvas.image];
    undoRedoStackIndex--;
}

// Gets called when the redo button is clicked
- (void)redoDrawing
{
    [undoManager redo];
    undoRedoStackIndex++;
}

- (void)resetImage
{
    NSLog(@"Hello"); // This NSLog message only appears when I click undo.
    pageView.canvas.image = [oldImagesArrays objectAtIndex:undoRedoStackIndex];
}

单击撤消或重做按钮时,应调用 resetImage ,并将当前图像设置为图像堆栈中的下一个或上一个对象(undoRedoStackIndex的当前值),这仅发生在我点击撤消,但不重做。

解决方案&& ||更好的方法是欣赏。

1 个答案:

答案 0 :(得分:6)

您无需跟踪更改,这是撤消管理器的用途。

制作一个像这样的可撤销方法:

- (void)setImage:(UIImage*)image
{
    if (_image != image)
    {
        [[_undoManager prepareWithInvocationTarget:self] setImage:_image]; // Here we let know the undo managed what image was used before
        [_image release];
        _image = [image retain];

        // post notifications to update UI
    }
}

就是这样。要撤消更改,只需致电[_undoManager undo],重新拨打[_undoManager redo]。当您告知撤消管理器撤消时,将使用旧映像调用此方法。如果您使用自定义按钮进行撤消操作,则可以使用[NSUndoManager canUndo]等来验证它。

撤消操作的数量没有限制。如果需要在某个时刻清理撤消堆栈,只需调用removeAllActions方法。