如何更改 NSTable 选定行的背景颜色?
这里是很好的答案,但它是为了合适的视图。
目前,我看到的是我可以更改选定的高亮样式:
MyTAble.SelectionHighlightStyle = NSTableViewSelectionHighlightStyle.Regular;
但这里只有3个选项;
None = -1L,
Regular,
SourceList
我尝试过以下解决方案:
patientListDelegate.SelectionChanged += (o, e) => {
var r = PatientTableView.SelectedRow;
var v = PatientTableView.GetRowView (r, false);
v.Emphasized = false;
};
它工作正常,但如果我最小化然后再次打开应用程序,仍然显示蓝色
我在 Objective-C 中找到了答案
这是c#实现:
内部代表:
public override NSTableRowView CoreGetRowView (NSTableView tableView, nint row)
{
var rowView = tableView.MakeView ("row", this);
if (rowView == null) {
rowView = new PatientTableRow ();
rowView.Identifier = "row";
}
return rowView as NSTableRowView;
}
和自定义行:
public class PatientTableRow : NSTableRowView
{
public override void DrawSelection (CGRect dirtyRect)
{
if (SelectionHighlightStyle != NSTableViewSelectionHighlightStyle.None) {
NSColor.FromCalibratedWhite (0.65f, 1.0f).SetStroke ();
NSColor.FromCalibratedWhite (0.82f, 1.0f).SetFill ();
var selectionPath = NSBezierPath.FromRoundedRect (dirtyRect, 0, 0);
selectionPath.Fill ();
selectionPath.Stroke ();
}
}
}
这是与已接受答案中相同技术的快速版本。重要细节:当控件不是按键或应用程序位于后台时,变量
isEmphasized
变为 false,因此可用于触发刷新并替换为不强调的颜色。
import AppKit
final class CustomTableRowView: NSTableRowView {
override func layout() {
super.layout()
// the default .none doesn’t call drawSelection(in:)
selectionHighlightStyle = .regular
}
override func drawSelection(in dirtyRect: NSRect) {
guard selectionHighlightStyle != .none else {
return
}
let selectionRect = NSInsetRect(bounds, 10, 0)
let fillColor = isEmphasized ? NSColor.red : NSColor.unemphasizedSelectedContentBackgroundColor
fillColor.setFill()
let selectionPath = NSBezierPath.init(roundedRect: selectionRect, xRadius: 5, yRadius: 5)
selectionPath.fill()
}
override var isEmphasized: Bool {
didSet {
needsDisplay = true
}
}
}
告诉 NSViewController 使用自定义单元格
// MARK: - NSOutlineViewDelegate
func outlineView(_ outlineView: NSOutlineView, rowViewForItem item: Any) -> NSTableRowView? {
CustomTableRowView()
}