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