Override paste: to format text
I would like to capture a string being pasted into a control and apply some custom formatting to the string开发者_StackOverflow社区 before being pasted.
How is this possible?
Thanks!
Override paste:
in your view/control (paste: is part of the UIResponderStandardEditActions
informal protocol). At the simplest, you'd do this:
- (void)paste:(id)sender
{
UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
NSString* rawString = pasteboard.string;
NSString* formattedString = // do something fun with rawString here
pasteboard.string = formattedString;
[super paste:sender];
}
This is assuming you don't need to do something terribly fancy with the string (like inserting animated smileys or something), in which case you shouldn't call super
but do the insertion yourself (if you are doing this on a UITextView
you can use the selectedRange
property to do the insertion properly).
EDIT: To get data from a NSPasteBoard
you should use –stringForType:
or one of several other data access methods. You might have to validate the string/data to make sure it's something that can be pasted.
You probably shouldn't call super
but use
[self insertText:formattedString];
if you're doing this on a NSTextView. If you're working with another class you have to find out what's appropriate in that context.
精彩评论