开发者

Override paste: to format text

开发者 https://www.devze.com 2022-12-20 20:46 出处:网络
I would like to capture a string being pasted into a control and apply some custom formattingto the string开发者_StackOverflow社区 before being pasted.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消