Tag: uitextview nsundomanager

如何在UITextView中用NSUndoManager支持replace文本?

我希望能够以编程方式replaceUITextView中的某些文本,所以我将此方法编写为UITextView类别: – (void) replaceCharactersInRange:(NSRange)range withString:(NSString *)newText{ self.scrollEnabled = NO; NSMutableString *textStorage = [self.text mutableCopy]; [textStorage replaceCharactersInRange:range withString:newText]; //replace text but undo manager is not working well [[self.undoManager prepareWithInvocationTarget:self] replaceCharactersInRange:NSMakeRange(range.location, newText.length) withString:[textStorage substringWithRange:range]]; NSLog(@"before replacing: canUndo:%d", [self.undoManager canUndo]); //prints YES self.text = textStorage; NSLog(@"after replacing: canUndo:%d", [self.undoManager canUndo]); //prints NO if (![self.undoManager isUndoing])[self.undoManager setActionName:@"replace characters"]; [textStorage […]