0

I am trying to cache the background color set for an NSTextField via the Interface Builder in a member variable for later usage in another component. At startup, the background color of the NSTextField is set to transparent.

@implementation CTTextField

- (id)initWithCoder:(NSCoder*)coder {
    self = [super initWithCoder:coder];
    if (self) {
        [self customize];
    }
    return self;
}

- (id)initWithFrame:(NSRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self customize];
    }
    return self;
}

- (void)awakeFromNib {
    ...
    [self customize];
}

- (void)customize {
    // Store the user defined background color.
    // FIXME: The color is not stored.
    m_userDefinedBackgroundColor = self.backgroundColor;
    // Disable the background color.
    self.backgroundColor = [NSColor colorWithCalibratedWhite:1.0f alpha:0.0f];
    ...
}

@end

However, m_userDefinedBackgroundColor is always black.
The whole CocoaThemes project I am working on is available at GitHub.

JJD
  • 50,076
  • 60
  • 203
  • 339

1 Answers1

0

Your -customize method is called twice. When nib is loading all objects are initializing with -initWithCoder: and after that receives -awakeFromNib. You should remove your -initWithCoder: or -awakeFromNib or check m_userDefinedBackgroundColor for nil in -customize like this:

- (void)customize {
    // Store the user defined background color.
    // FIXME: The color is not stored.

    if (m_userDefinedBackgroundColor == nil)
        m_userDefinedBackgroundColor = self.backgroundColor;

    // Disable the background color.
    self.backgroundColor = [NSColor colorWithCalibratedWhite:1.0f alpha:0.0f];
    ...
}
Dmitry
  • 7,300
  • 6
  • 32
  • 55
  • I agree with the redundant call but this does not answer my question why the background color defined via Interface Builder is not stored. – JJD Jul 31 '12 at 07:46
  • Because after first call of `-customize` you overwrite `self.backgroundColor` and the second time you set `m_userDefinedBackgroundColor` to this overwritten value and loose the original value. I've added the code to my answer. – Dmitry Jul 31 '12 at 08:52