UITextView undo manager do not work with replaceme

2019-06-27 23:27发布

问题:

iOS 6 has been updated to use UITextView for rich text editing (a UITextView now earns an attributedText property —which is stupidly non mutable—). Here is a question asked on iOS 6 Apple forum under NDA, that can be made public since iOS 6 is now public...

In a UITextView, I can undo any font change but cannot undo a replacement in a copy of the view's attributed string. When using this code...

- (void) replace: (NSAttributedString*) old with: (NSAttributedString*) new

{
1.    [[myView.undoManager prepareWithInvocationTarget:self] replace:new with:old];
2.    old=new;

}

... undoing is working well.

But if I add a line to get the result visible in my view, the undoManager do not fire the "replace:with:" method as it should...

- (void) replace: (NSAttributedString*) old with: (NSAttributedString*) new

{
1.    [[myView.undoManager prepareWithInvocationTarget:self] replace:new with:old];
2.    old=new;
3.    myView.attributedText=[[NSAttributedString alloc] initWithAttributedString:old];

}

Any idea? I have the same problem with any of the replacement methods, using a range or not, for MutableAttributedString I tried to use on line "2"...

回答1:

Umm, wow I really didn't expect this to work! I couldn't find a solution so I just started trying anything and everything...

- (void)applyAttributesToSelection:(NSDictionary*)attributes {
    UITextView *textView = self.contentCell.textView;

    NSRange selectedRange = textView.selectedRange;
    UITextRange *selectedTextRange = textView.selectedTextRange;
    NSAttributedString *selectedText = [textView.textStorage attributedSubstringFromRange:selectedRange];

    [textView.undoManager beginUndoGrouping];
    [textView replaceRange:selectedTextRange withText:selectedText.string];
    [textView.textStorage addAttributes:attributes range:selectedRange];
    [textView.undoManager endUndoGrouping];

    [textView setTypingAttributes:attributes];
}


回答2:

The Undo Manager is reset after setting its 'text' or 'attributedText' property, this is why it does not work. Whether this behavior is a bug or by design I don't know.

However, you can use the UITextInput protocol method instead.

  • (void)replaceRange:(UITextRange *)range withText:(NSString *)text

This works.