0

我想通过Interface Builder中的NSTextField为成员变量中的NSTextField设置背景颜色,以便以后在另一个组件中使用。启动时,NSTextField的背景颜色设置为透明。无法存储通过InterfaceBuilder设置的NSTextField的背景颜色

@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 

然而,m_userDefinedBackgroundColor总是
整个CocoaThemes project我正在使用的是GitHub。

回答

0

您的-customize方法被调用两次。当加载笔尖时,所有对象正在使用-initWithCoder:进行初始化,之后接收到-awakeFromNib。你应该在-customize这样的nil删除您-initWithCoder:-awakeFromNib或检查m_userDefinedBackgroundColor

- (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]; 
    ... 
} 
+0

我同意冗余呼叫但为什么通过界面生成器中定义的背景颜色不存储在这个不回答我的问题。 – JJD 2012-07-31 07:46:58

+0

因为在第一次调用'-customize'后,您覆盖'self.backgroundColor',并且第二次将'm_userDefinedBackgroundColor'设置为覆盖的值并丢失原始值。我已将代码添加到我的答案中。 – Dmitry 2012-07-31 08:52:13