-1
我寫了簡單的撤消和重做根據NSUndoManager的示例代碼更改背景顏色。所有的東西都可以很好地與撤消動作配合使用。但使用重做,它不會跳轉到之前註冊的NSUndoManager的註冊方法。 跟蹤代碼:關於你加什麼NSUndoManager only撤消,不是重做
#import "ViewController.h"
enum color {kWhite = 0, kRed, kOrange, kYellow, kGreen, kCyan, kBlue, kMagenta};
@interface ViewController(){
enum color kColor;
NSArray * colorArr;
NSUndoManager * undoManager;
}
- (IBAction)changeColor:(id)sender;
- (IBAction)undo:(id)sender;
- (IBAction)redo:(id)sender;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.]
kColor = kWhite;
colorArr = [NSArray arrayWithObjects:[UIColor whiteColor], [UIColor redColor], [UIColor orangeColor], [UIColor yellowColor], [UIColor greenColor], [UIColor cyanColor], [UIColor blueColor], [UIColor magentaColor], nil];
undoManager = [[NSUndoManager alloc] init];
undoManager.levelsOfUndo = 7;
NSNotificationCenter * nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:@selector(undoManagerDidUndo:) name:NSUndoManagerDidUndoChangeNotification object:self.undoManager];
[nc addObserver:self selector:@selector(undoManagerDidRedo:) name:NSUndoManagerDidRedoChangeNotification object:self.undoManager];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)changeColor:(id)sender {
[[undoManager prepareWithInvocationTarget:self]
setcolor:kColor];
kColor ++;
if(kColor > kMagenta) kColor = kWhite;
[self.view setBackgroundColor:colorArr[kColor]];
}
-(void) setcolor:(enum color) color{
kColor = color;
[self.view setBackgroundColor:colorArr[kColor]];
NSLog(@"zzzz %d", color);
};
- (IBAction)undo:(id)sender {
[undoManager undo];
}
- (IBAction)redo:(id)sender {
[undoManager redo];
}
#pragma mark - Undo support
// -------------------------------------------------------------------------------
// undoManagerDidUndo:
// Handler for the NSUndoManagerDidUndoChangeNotification. Redisplays the table
// view to reflect the changed value.
// See also: -setEditing:animated:
// -------------------------------------------------------------------------------
- (void)undoManagerDidUndo:(NSNotification *)notification
{
//[self.view setBackgroundColor:colorArr[kColor]];
}
// -------------------------------------------------------------------------------
// undoManagerDidRedo:
// Handler for the NSUndoManagerDidRedoChangeNotification. Redisplays the table
// view to reflect the changed value.
// See also: -setEditing:animated:
// -------------------------------------------------------------------------------
- (void)undoManagerDidRedo:(NSNotification *)notification
{
//[self.view setBackgroundColor:colorArr[kColor]];
}
@end
也許幾句/修改會有所幫助。 – benka