0

I want to configure some text before 'fully pasting' it into an NSTextField.

Is there an (easy) way to detect if the user is pasting text rather than writing it into a NSTextField in Swift?

power_N_9
  • 35
  • 1
  • 6
  • 1
    Here's an idea: I'm not posting as an answer right now because I haven't tested this and don't really have that sort of time, but you can try to use the Interface Builder to link the Edit menu > Paste button to your own function. This will allow you to do things when users paste stuff. – Arc676 May 21 '16 at 09:06

2 Answers2

0

Why don't you check the size of the changes? You can implement the delegate method, and do something like:

func textDidChange(notification: NSNotification) {
let textField = notification.object
let newTextLength = textField.text.characters.count
...

You can now compare the length of the text with the previous one (that you'll store somewhere), if it's changing by more than 1 character, then the user is pasting something. I hope this helps.

Flavio Silverio
  • 1,004
  • 8
  • 12
  • That does not detect whether a text is typed or if it is pasted... It only detects if something changed, the the way it is changed. – Zaphod May 20 '16 at 14:34
  • @Zaphod Doesn't that apply to many things? We observe something that implies something else and we assume that the implied action occurred. – Arc676 May 20 '16 at 14:45
  • @Zaphod, this way you can detect the user is pasting it. unless he's pasting only 1 character at a time. You probably can also use some kind of method swizzling to get the paste: selector. I would not recommend swizzling thought. – Flavio Silverio May 20 '16 at 15:38
  • Unfortunately that does not really work; I tried to put a listener on the paste selector, but somehow I never run into it.. The thing is, I have a textField with a limited capacity, and when a user pastes text into it, I want to put the 'rest' of the characters that do not fit into this textfield into in another one. – power_N_9 May 25 '16 at 07:32
  • what if you want to detect the user trying to paste an image into a textfield so that you can intercept the paste and move the image to an image well. – jiminybob99 Aug 09 '16 at 06:05
0

A nstextfield does not have copy and paste functions. Those are only found in nstextview. the catch is that when a textfield is edited it opens up a textview called a fieldeditor during the editing.

See my answer here:

NSTextField: exposing its Copy and Paste methods

Community
  • 1
  • 1
jiminybob99
  • 857
  • 1
  • 8
  • 15