Como posso substituir o texto no UITextView pelo suporte ao NSUndoManage
Eu quero poder substituir algum texto em um UITextView programaticamente, então escrevi esse método como uma categoria 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;
}
Funciona, mas o NSUndoManager para de funcionar (parece ter sido redefinido) logo após executarself.text=textStorage
Encontrei uma API privada:-insertText:(NSString *)
que pode fazer o trabalho, mas quem sabe se a Apple vai aprovar meu aplicativo se eu o usar. Existe alguma maneira de substituir o texto no UITextView com o suporte do NSUndoManager? Ou talvez esteja faltando alguma coisa aqui?