6

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

我的应用程序是一个绘画/笔记应用程序,我有一个撤消/重做堆栈,最后十个UIImages(我不知道这是否是最有效的方式)在一个数组中。当用户对当前图像进行更改时,旧图像被压入堆栈,如果数组已经有十个对象,则删除数组中的第一个图像。我有一个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 的当前值),这仅在我单击撤消时发生,而不是重做时发生。

解决方案 && || 更好的方法将不胜感激。

4

1 回答 1

7

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

像这样创建一个可撤销的方法:

- (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方法。

于 2011-11-23T23:49:03.153 回答