views:

139

answers:

1

Hello,

I would like to capture a string being pasted into a control and apply some custom formatting to the string before being pasted.

How is this possible?

Thanks!

+4  A: 

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.

Felixyz
Perfect, thanks!
christo16
I guess I tagged this post with iPhone, but I'm looking more for implementation for NSPasteBoard, specifically the [super paste:sender] part.
christo16
@haroldthehungry See the edit.
Felixyz