[英]Custom NSTableCellView labels not changing text color when selected
我有一個帶有3個文本字段的自定義NSTableCellView
,1個出現,另外2個是我自己創建的。 這是問題所在:
即使單擊該行,文本字段的文本顏色也保持不變。 我試圖實現我通過谷歌搜索發現的代碼,但它不起作用。 我的自定義NSTableCellView代碼是:
- (void)drawRect:(NSRect)dirtyRect{
NSColor *color = [NSColor colorWithCalibratedRed:(26/255.0) green:(26/255.0) blue:(26/255.0) alpha:1.0];
[self.textField setTextColor:color];
color = [NSColor colorWithCalibratedRed:(102/255.0) green:(102/255.0) blue:(102/255.0) alpha:1.0];
[_lbl1 setTextColor:color];
[_lbl2 setTextColor:color];
}
- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
NSColor *color = (backgroundStyle == NSBackgroundStyleDark) ? [NSColor windowBackgroundColor] : [NSColor controlShadowColor];
self.textField.textColor = color;
self.lbl1.textColor = color;
self.lbl2.textColor = color;
[super setBackgroundStyle:backgroundStyle];
}
當用戶點擊標簽時,我該怎么做才能使標簽的文字顏色變白?
實際上,在NSTableViewCell上覆蓋setBackgroundStyle對我來說非常有效,至少在OS X 10.8上是這樣。 它會根據選擇事件和窗口激活/停用進行更新。
這是我的自定義單元格impl - 盡可能簡單:
@implementation RuntimeInstanceCellView
- (void)setBackgroundStyle:(NSBackgroundStyle)backgroundStyle {
[super setBackgroundStyle:backgroundStyle];
self.detailTextField.textColor = (backgroundStyle == NSBackgroundStyleLight ? [NSColor darkGrayColor] : [NSColor colorWithCalibratedWhite:0.85 alpha:1.0]);
// self.detailTextField.textColor = (backgroundStyle == NSBackgroundStyleLight ? [NSColor blackColor] : [NSColor whiteColor]);
}
@end
擴展了已接受的答案,在Swift 2.0中,這個過程略有不同。 覆蓋NSTableCellView
子類的backgroundStyle
屬性以添加didSet 屬性observer :
class CustomTableCellView: NSTableCellView {
@IBOutlet weak var detailTextField: NSTextField!
override var backgroundStyle: NSBackgroundStyle {
didSet {
if self.backgroundStyle == .Light {
self.detailTextField.textColor = NSColor.controlTextColor()
} else if self.backgroundStyle == .Dark {
self.detailTextField.textColor = NSColor.alternateSelectedControlTextColor()
}
}
}
}
對於Swift 3和4(這不是很有趣嗎?):
override var backgroundStyle: NSView.BackgroundStyle {
didSet {
if self.backgroundStyle == .light {
self.detailTextField.textColor = NSColor.controlTextColor
} else if self.backgroundStyle == .dark {
self.detailTextField.textColor = NSColor.alternateSelectedControlTextColor
}
}
}
在你的tableViewSelectionDidChange
獲取單元格
UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath]; //replace UITableViewCell with your customCell class name if it other
//now as u got the instance of your cell u can modify the labels in it, like
cell.lable1.textColor = [UIColor whiteColor];
這對你有用。
在此之后再次選擇其他單元格時可能會出現問題,此時前一單元格可能仍有白色標簽。 如果這會導致問題,那么在頭類中只有一個NSIndexPath
實例表示以前選擇的indexPath,使用此實例可以在選擇新單元格后設置回默認顏色。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.