Joh*_*nny 6 macos cocoa objective-c
我正在尝试在选择表行时实现自定义行颜色.
-(void)tableViewSelectionDidChange:(NSNotification *)notification{
NSInteger selectedRow = [_mainTable selectedRow];
NSTableCellView *cell = [_mainTable rowViewAtRow:selectedRow makeIfNecessary:NO];
cell.layer.backgroundColor = [NSColor redColor].CGColor;
NSLog(@"selected");
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.我发现Apple文档很混乱(也许我错了).我对Mac编程没有经验.
有人建议任何解决方案?基本上我需要选择颜色是透明的.
min*_*pop 12
解
这应该通过子类化NSTableRowView然后使用NSTableView委托方法返回子类来完成
-(NSTableRowView*)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
NSTableRowView修改行视图时,子类提供了更大的灵活性.在NSTableView上面的委托方法中返回您的子类也会在从一行到另一行的单击时自动删除背景选择颜色(这是在提供的另一个答案中的一个未解决的问题).
脚步
首先,子类NSTableRowView和覆盖drawSelectionInRect以在选择时更改其背景颜色:
@implementation MyTableRowView
- (void)drawSelectionInRect:(NSRect)dirtyRect
{
[super drawSelectionInRect:dirtyRect];
[[NSColor yellowColor] setFill];
NSRectFill(dirtyRect);
}
Run Code Online (Sandbox Code Playgroud)
接下来,使用rowViewForRow NSTableView委托方法返回子类行视图:
- (NSTableRowView*)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row
{
static NSString* const kRowIdentifier = @"MyTableRow";
MyTableRowView* myRowView = [tableView makeViewWithIdentifier:kRowIdentifier owner:self];
if (!myRowView) {
myRowView = [[MyTableRowView alloc] initWithFrame:NSZeroRect];
myRowView.identifier = kRowIdentifier;
}
return rowView;
}
Run Code Online (Sandbox Code Playgroud)
使用此方法,您还可以轻松覆盖其他元素,如分隔符颜色.为此,请覆盖子类中的drawSeparatorInRect方法,NSTableRowView如下所示:
- (void)drawSeparatorInRect:(NSRect)dirtyRect
{
// Change the separator color if the row is selected
if (self.isSelected) [[NSColor orangeColor] setFill];
else [[NSColor grayColor] setFill];
// Fill the seperator
dirtyRect.origin.y = dirtyRect.size.height - 1.0;
dirtyRect.size.height = 1.0;
NSRectFill(dirtyRect);
}
Run Code Online (Sandbox Code Playgroud)
资源
覆盖NSTableRowView显示设置
https://developer.apple.com/reference/appkit/nstablerowview
NSTableview rowViewForRow委托方法
https://developer.apple.com/reference/appkit/nstableviewdelegate/1532417-tableview
首先设置tableview选择高亮样式
NSTableViewSelectionHighlightStyleNone
Run Code Online (Sandbox Code Playgroud)
然后在你的tablView委托工具中
tableView:shouldSelectRow:
Run Code Online (Sandbox Code Playgroud)
并在其中编写此代码:
NSTableViewRow *row= [_mainTable rowViewAtRow:selectedRow makeIfNecessary:NO];
row.backgroundColor = [your color];
return YES;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6202 次 |
| 最近记录: |