Skip to content

Instantly share code, notes, and snippets.

@hoshi-takanori
Last active February 11, 2020 23:07
Show Gist options
  • Save hoshi-takanori/8192216 to your computer and use it in GitHub Desktop.
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)
#import <UIKit/UIKit.h>
@interface MyTextView : UITextView
- (void)replaceSelectionWithAttributedText:(NSAttributedString *)text;
- (void)replaceRange:(NSRange)range withAttributedText:(NSAttributedString *)text;
@end
#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
@chockenberry
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment