2011-03-05 67 views
1

我試圖在選中單元格時更改NSTextFieldCell的背景顏色。在選擇時更改NSTextFieldCell背景顏色

這是代碼:

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { 

    [super drawWithFrame:cellFrame inView:controlView]; 

    if([self isHighlighted]) { 
     [self setBackgroundColor:[NSColor whiteColor]]; 
    } 
} 

但所選行始終藍色。我錯過了什麼?

注意:這不是iOS應用程序。

非常感謝您。

回答

5

這是不容易的,因爲我認爲之前: NStableview有一些問題。如果妳使用類似:

[destinationsListForSaleTableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone]; 

你要做

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex 
{ 
if ([[aTableView selectedRowIndexes] containsIndex:rowIndex]) { 
    [aCell setBackgroundColor: [NSColor colorWithDeviceRed:0.29 green:0.27 blue:0.42 alpha:1]]; 

} else [aCell setBackgroundColor: [NSColor colorWithDeviceRed:0.52 green:0.54 blue:0.70 alpha:1]]; 
[aCell setDrawsBackground:YES]; 

} 

這是不夠的,如果U型線是不是定製的。 如果你改變高度和內部,它必須更復雜:

保留選擇風格表供您選擇。 在細胞亞類:

-(NSColor *)highlightColorWithFrame:(NSRect)cellFrame inView:(NSView *)controlView { 
return nil; 
//[NSColor colorWithDeviceRed:0.29 green:0.27 blue:0.42 alpha:1]; 
} 

- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView 
{ 
if ([self isHighlighted]) { 
    [[NSColor colorWithDeviceRed:0.29 green:0.27 blue:0.42 alpha:1] set]; 
    cellFrame.origin.x -= 1; 
    cellFrame.origin.y -= 1; 
    cellFrame.size.height += 2; 
    cellFrame.size.width += 3; 

    NSRectFill(cellFrame); 

} 
[super drawWithFrame:cellFrame inView:controlView]; 
} 

你問我爲什麼改變填充的大小? 當你使用背景的時候,蘋果留下一個小盒子,它會有不同的顏色。

+0

感謝你,setDrawsBackground:YES是我失蹤。 – nebs 2011-12-21 23:43:29

-1

不要這樣做。相反,當您在-tableView:cellForRowAtIndexPath:中創建單元格時,請將該單元格的「selectedBackgroundView」屬性設置爲一個視圖,該視圖將在選中該單元格時變爲背景。這可以只是一個普通的舊UIView與你的背景顏色。我在UIView上創建了一個名爲+ backgroundViewForTableCell:的方法,它完全實現了一個視圖並將其背景顏色設置爲我想要的顏色。我這樣使用它,當我創建單元格:

cell.selectedBackgroundView = [UIView backgroundViewForTableCell:cell]; 

你可能要當細胞被竊聽做的另一件事是設置在單元格中的任何文本的顏色。例如,如果背景顏色相對較暗,則可能需要將文本顏色從黑色更改爲白色。

+0

我不是爲iOS編程的,但是謝謝,這非常有用。 :) – Donovan 2011-03-05 17:33:43

+0

對不起 - 我應該仔細閱讀。 – Caleb 2011-03-05 17:46:49