Changing NSTextFieldCell background color on selection
I'm trying to change the background color of a NSTextFieldCell when the cell is selected.
This is the code:
- (void)drawWithFrame:(NSRect)cellFrame inView:(NSView *)controlView {
[super drawWithFrame:cellFrame inView:controlView];
if([self isHighlighted]) {
[self setBackgroundColor:[NSColor whiteColor]];
}
}
But the selected row is always blue. I am missing something?
Note: this is not an iOS application.
Thanks you in ad开发者_StackOverflowvance.
This is not easy as i think before: NStableview have some problem there. If u using something like:
[destinationsListForSaleTableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone];
You have to do
- (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];
}
This is enough if u cell is not custom. If u change height and interior, it have to be more complicated:
keep selection style table for you choice. In cell subclass:
-(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];
}
You ask me why i change size of filling? Bcs when u using background, apple leave a small box, which will have different color.
Don't do it that way. Instead, when you create the cell in your -tableView:cellForRowAtIndexPath:, set the cell's "selectedBackgroundView" property to a view that will become the background when the cell is selected. This can be just a plain old UIView with your background color. I created a category on UIView that has a method called +backgroundViewForTableCell:, which does exactly that... instantiates a view and sets its background color to the color I want. I use it like this when I create the cell:
cell.selectedBackgroundView = [UIView backgroundViewForTableCell:cell];
The other thing you might want to do when the cell is tapped is to set the color of any text in the cell. If your background color is relatively dark you might want to change the text color from black to white, for example.
精彩评论