title: Subclassing an NSTextField
body: <p>Given all the complex things I seem to cover every day, this appears to be a "what the heck am I doing wrong that seems to simple?" scenario!</p>
  
  <p>I would like to subclass an <code>NSTextField</code> to change the background color and text color. For simplicity sake (and to help anyone who hasn't ever subclassed anything before), here is the example of my (simplified) subclass <code>MyNSTextFieldSubclass</code>...</p>
  
  <p><strong>Step 1:</strong></p>
  
  <p>Create the subclass file:</p>
  
  <p>First the header file</p>
  
  <pre><code>@interface MyTextFieldSubclass : NSTextField {
  }
  
  @end
  </code></pre>
  
  <p>And the method file</p>
  
  <pre><code>@implementation MyTextFieldSubclass
  
  -(NSColor *)backgroundColor {
      return [NSColor redColor];
  }
  
  -(NSColor *)textColor {
      return [NSColor yellowColor];
  }
  
  @end
  </code></pre>
  
  <p><strong>Step 2:</strong></p>
  
  <p>Drag an <code>NSTextField</code> to a window in Interface Builder, select the <code>Identity</code> tab in the inspector and select the class <code>MyTextFieldSubclass</code></p>
  
  <p><strong>Step 3:</strong></p>
  
  <p>Save the IB file, build and run the application</p>
  
  <p><strong>Problem</strong></p>
  
  <p>When I run the build, the text field does not reflect the color subclassing. However, I know the subclass is being called because if I add the following method, it gets called on text changes.</p>
  
  <pre><code>-(void)textDidChange:(NSNotification *)notification {
      NSLog(@"My text changed");
  }
  </code></pre>
  
  <p>So why does the color change not occur on the text fields?</p>
  
  <p>I know that I can set the color in IB, but for anyone who has dealt with a <em>lot</em> of UI elements that all need the same styling, subclassing makes life way, way easier.</p>
  
  <p>Ironically, I have never had to subclass an <code>NSTextField</code> before and this one has me stumped.</p>
  
  <p>As usual, any and all help very much appreciated. I'm sure it will turn out to be a "Doh!" moment - just cant see the wood for the trees right now (plus I'm exhausted from watching too much World Cup Football early in the morning which never helps).</p>
  
  <p><strong>=== SOLUTION ===</strong></p>
  
  <p>As offered by Jaanus the solution is to put it into the <code>viewWillDraw</code> method. Thus my (simplified) method would now look like this:</p>
  
  <pre><code>@implementation MyTextFieldSubclass
  
  -(void)viewWillDraw {
      [super setBackgroundColor:[NSColor redColor]];
      [super setTextColor:[NSColor yellowColor]];
  }
  
  @end
  </code></pre>
  
  <p>Thanks guys for your help.</p>