【发布时间】:2011-06-21 02:49:30
【问题描述】:
我希望能够以编程方式替换 UITextView 中的一些文本,因此我将此方法编写为 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 release];
//new range:
range.location = range.location + newText.length;
range.length = 0;
self.selectedRange = range;
self.scrollEnabled = YES;
}
它可以工作,但 NSUndoManager 在完成 self.text=textStorage 之后就停止工作(它似乎被重置)我找到了一个私有 API:-insertText:(NSString *) 可以完成这项工作,但如果我知道苹果是否会批准我的应用程序,谁知道用它。有什么方法可以用 NSUndoManager 支持在 UITextView 中替换文本?或者我在这里遗漏了什么?
【问题讨论】:
标签: iphone ios objective-c uitextview nsundomanager