title: NSTextField : How to draw background only when focused
body: <p>I put a textfield in a window, and I want the textfield draw background only when focused.
  I know that all the controls in the window share one field editor.
  I tried subclass nstextfield and implement becomeFirstResponder and resignFirstResponder.
  And tried use custom singleton editor for the window . </p>
  
  <p>Any one know how to achieve this?</p>
  
  <hr>
  
  <p>In the NSWindow ,every textfield or button share one instance of field editor(a singleton NSTextView instance),so when you click the textfield, textfield become firstResponser first,and then quickly pass it to the shared field editor. So when the textfield lost focus ,the resignFirstResponder of the textfield will never be called（because the field editor is the FirstResponder now）.</p>
  
  <p>You can look at fieldEditor:forObject: in NSWindow API. 
  <a href="http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/fieldEditor:forObject" rel="nofollow">http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/ApplicationKit/Classes/NSWindow_Class/Reference/Reference.html#//apple_ref/occ/instm/NSWindow/fieldEditor:forObject</a>:</p>
  
  <hr>
  
  <p><strong>SOLUTION:</strong>
   (Thanks , Michael Gorbach)
  In my window controller </p>
  
  
  
  <pre class="lang-c prettyprint-override"><code>- (id)windowWillReturnFieldEditor:(NSWindow *)sender toObject:(id)anObject
  {
      NSText *text = [sender fieldEditor:YES forObject:self];
      if(text&amp;&amp;[anObject isKindOfClass:[MyCustomTextField class]])
      {
          [text setBackgroundColor:[NSColor whiteColor]];
          [text setDrawsBackground:YES];
      }
      return text;
  }
  </code></pre>