Last active
February 11, 2020 23:07
-
-
Save hoshi-takanori/8192216 to your computer and use it in GitHub Desktop.
UITextView subclass to replace range with attributed text, with undo/redo support. (iOS 7 only)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <UIKit/UIKit.h> | |
@interface MyTextView : UITextView | |
- (void)replaceSelectionWithAttributedText:(NSAttributedString *)text; | |
- (void)replaceRange:(NSRange)range withAttributedText:(NSAttributedString *)text; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "MyTextView.h" | |
@implementation MyTextView | |
- (void)replaceSelectionWithAttributedText:(NSAttributedString *)text | |
{ | |
[self replaceRange:self.selectedRange withAttributedText:text]; | |
} | |
- (void)replaceRange:(NSRange)range withAttributedText:(NSAttributedString *)text | |
{ | |
[self replaceRange:range withAttributedText:text andSelectRange:NSMakeRange(range.location, text.length)]; | |
} | |
- (void)replaceRange:(NSRange)range withAttributedText:(NSAttributedString *)text andSelectRange:(NSRange)selection | |
{ | |
[[self.undoManager prepareWithInvocationTarget:self] replaceRange:NSMakeRange(range.location, text.length) | |
withAttributedText:[self.attributedText attributedSubstringFromRange:range] | |
andSelectRange:self.selectedRange]; | |
[self.textStorage replaceCharactersInRange:range withAttributedString:text]; | |
self.selectedRange = selection; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've been struggling with this for several hours and this is a simple and complete solution to the problem of pasting attributed text into a UITextView. Thank you!