UITextView undo manager do not work with replacement attributed string (iOS 6)

浪子不回头ぞ 提交于 2019-12-10 15:49:14

问题


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.



来源:https://stackoverflow.com/questions/12501541/uitextview-undo-manager-do-not-work-with-replacement-attributed-string-ios-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!