本文介绍了如何使用NSUndoManager支持替换UITextView中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够以编程方式替换UITextView中的某些文本,因此我将此方法编写为UITextView类别:

I want to be able to replace some text in an UITextView programatically, so I wrote this method as an UITextView category:

- (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 *) that可以做这个工作,但谁知道如果我使用它,Apple是否会批准我的应用程序。有没有办法在UITextView中使用NSUndoManager支持替换文本?或许我在这里遗漏了一些东西?

It works but NSUndoManager stops working (it seems to be reset) just after doing self.text=textStorage I have found a private API: -insertText:(NSString *) that can do the job but who knows if Apple is going to approve my app if I use it. Is there any way to get text replaced in UITextView with NSUndoManager Support? Or maybe I am missing something here?

推荐答案

实际上没有任何黑客或自定义类别可以实现此目的。您可以使用内置的UITextInput协议方法 replaceRange:withText:。要插入文本,您只需:

There is actually no reason for any hacks or custom categories to accomplish this. You can use the built in UITextInput Protocol method replaceRange:withText:. For inserting text you can simply do:

[textView replaceRange:textView.selectedTextRange withText:replacementText];

这适用于iOS 5.0。撤消自动工作,没有奇怪的滚动问题。

This works as of iOS 5.0. Undo works automatically and there are no weird scrolling issues.

这篇关于如何使用NSUndoManager支持替换UITextView中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-29 19:01