我是一个狂热的16岁程序员,现在我正在开发一个应用程序,一个简单的应用程序,它只有一个将整数加1的按钮,并将其显示在标签中,我想添加一个撤消按钮。根据我的研究,NSUndoManager应该是有帮助的。问题是我不能让它工作!这个问题可能看起来很明显,但我已经从youtube上学到了所有我知道的东西,因此我不知道很多东西。这是我的代码:
@implementation ViewController
NSUndoManager *undoManager;
-(IBAction)add1:(id)sender{
Count = Count + 1;
Counter.text = [NSString stringWithFormat:@"%i", Count];
[undoManager prepareWithInvocationTarget:self];
[undoManager registerUndoWithTarget:self selector:@selector(add1:) object:Counter.text];
[undoManager setActionName:NSLocalizedString(@"actions.update", @"Update Score")];
}
-(IBAction)Undo:(id)sender{
[undoManager undo];
Counter.text = [NSString stringWithFormat:@"%i", Count];
}
- (void)viewDidLoad {
Count = 0;
undoManager =[[NSUndoManager alloc]init];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end当你回答时,请尽量不要说非常专业的词语,或者如果你确实定义了它们,因为正如我之前所说的,我不知道很多事情,我可能听不懂你说的话,我真的很想学习这一点。我的应用程序的一个示例代码,但如果NSUndoManager编程正确,那就太好了,这样我就可以比较它,找出我的错误是什么。
谢谢!
发布于 2015-03-25 05:38:23
您需要一个与-add1:方法相反的方法。然后,您需要将其设置为撤消操作的选择器:
- (IBAction) add1:(id)sender
{
Count = Count + 1;
Counter.text = [NSString stringWithFormat:@"%i", Count];
[undoManager registerUndoWithTarget:self selector:@selector(subtract1:) object:sender];
[undoManager setActionName:NSLocalizedString(@"Increment Score", @"Name for undo action")];
}
- (IBAction) subtract1:(id)sender
{
Count = Count - 1;
Counter.text = [NSString stringWithFormat:@"%i", Count];
[undoManager registerUndoWithTarget:self selector:@selector(add1:) object:sender];
[undoManager setActionName:NSLocalizedString(@"Decrement Score", @"Name for undo action")];
}因此,撤消-add1:的方法是调用-subtract1:,撤消-subtract1:的方法是调用-add1:。此外,由于-subtract1:注册了一个撤消操作,这意味着您获得了重做功能。(如果用户选择重做他们撤消的操作,则在撤消过程中注册的撤消操作被理解为重做操作。)
注意:当您使用-registerUndoWithTarget:...时,您不使用-prepareWithInvocationTarget:。你可以选择其中的一个。
此外,您的-Undo:方法不应该需要设置Counter.text,因为这应该由undo操作自动完成。
https://stackoverflow.com/questions/29242302
复制相似问题