我正在尝试NSUndoManager
在我的 iOS 应用程序中实现一个。我让撤消功能工作,但不是重做部分。我对 iOS 开发很陌生,这是我第一次使用NSUndoManager
,所以它可能是微不足道的。
我的应用程序是一个绘画/笔记应用程序,我有一个撤消/重做堆栈,最后十个UIImage
s(我不知道这是否是最有效的方式)在一个数组中。当用户对当前图像进行更改时,旧图像被压入堆栈,如果数组已经有十个对象,则删除数组中的第一个图像。我有一个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 的当前值),这仅在我单击撤消时发生,而不是重做时发生。
解决方案 && || 更好的方法将不胜感激。