【问题标题】:Custom NSTextField in table view: how do I know if the row is selected to change the background color?表格视图中的自定义 NSTextField:如何知道是否选择了该行来更改背景颜色?
【发布时间】:2012-01-18 09:49:11
【问题描述】:

我有基于视图的 NSTableView 和自定义 NSTextField 子类实例来绘制行标签。

根据是否选择(突出显示)行,我想更改自定义文本字段的背景颜色。

我如何知道我的文本字段的drawRect:(NSRect)dirtyRect 是否选择了父表行?

文本字段甚至不知道它是表格视图的一部分(而且不应该这样做)。

如果我将一个普通的NSTextField 放入表格视图中,它会根据行选择状态自动更改其字体颜色,因此文本字段必须以某种方式知道它是被选中/突出显示还是现在。

【问题讨论】:

    标签: cocoa nstableview nstextfield


    【解决方案1】:

    表格视图是单元格视图中视图的父视图。 因此,您可以在 drawRect 方法中迭代视图层次结构以找到父表视图。 并检查是否选择了包含自定义 NSTextField 的行。

    override public func drawRect(dirtyRect: NSRect) {
        var backgroundColor = NSColor.controlColor() //Replace by the non selected color
        var parentView = superview
        while parentView != nil {
            if let tableView = parentView as? NSTableView {
                let row = tableView.rowForView(self)
                if tableView.isRowSelected(row) {
                    backgroundColor = NSColor.alternateSelectedControlColor() //Replace by the selected background color
                }
                break
            }
            parentView = parentView?.superview
        }
        //Perform the drawing with the backgroundColor
       // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-15
      • 2016-01-15
      • 2014-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多