cocoa - 如何在 Interface Builder 中构建 NSTableRowView 原型(prototype)

标签 cocoa interface-builder nstableview nstablerowview

我有一个基于 View 的 NSTableView,我正在尝试自定义某些行的外观。

我知道我需要实现标题中提到的委托(delegate)方法;但我不知道该怎么做。

文档说:

You can use the delegate method tableView:rowViewForRow: to customize row views. You typically use Interface Builder to design and lay out NSTableRowView prototype rows within the table. As with prototype cells, prototype rows are retrieved programmatically at runtime. Implementation of NSTableRowView subclasses is entirely optional.

但是,与单元格不同,界面构建器中没有 NSTableRowView 类,也不清楚如何设置“原型(prototype)”行 View 。

我正在尝试这样的事情(Swift 3):

func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView?
{
    if (row % 4) == 0 {
        // .................................................. 
        // [ A ] SPECIAL ROW:

        if let rowView = tableView.make(withIdentifier: "SpecialRow", owner: self) as? NSTableRowView {

            rowView.backgroundColor = NSColor.gray()
            return rowView
        }
        else {
            return nil
        }

        // ^ Always returns nil (Because I don't know how
        // to setup the prototype in Interface Builder)
    }
    else{
        // ..................................................
        // [ B ] NORMAL ROW (No customization needed)

        return nil
    } 
}

我有类似的代码适用于单元格 - 即-tableView:viewForTableColumn:row:

最佳答案

好的,所以显而易见的(?)解决方案有效:

  1. 在 Interface Builder 上,将普通 NSView 拖放到表格中(它只接受特定列中的拖放,作为 TableView 的直接子级)。

  2. 转到刚刚删除的 View 的身份检查器,并将其类更改为“NSTableRowView”。

  3. 因为在我的代码中仅设置 .backgroundColor 属性不起作用,所以我使用了 this solution并添加了一个框 View 作为 subview ,并在 Interface Builder 中对其进行了配置。我必须在框和行 View 之间设置自动布局约束,以便它在运行时拉伸(stretch)到行 View 的实际大小。

(或者,我可以使用行 View 的 wantsLayer 属性...)

<小时/>

更新:事实证明,我在代码中使用的backgroundColor属性是在NSTableRowView(NSView)中定义的> 没有这样的属性,与 UIView 不同)。

但它也会被 TableView 的设置覆盖(即是否交替行),所以我应该在这个方法中自定义它:

func tableView(_ tableView: NSTableView, didAdd rowView: NSTableRowView, forRow row: Int)
{
    if (row % 4) == 0 {
        rowView.backgroundColor = NSColor.controlAlternatingRowBackgroundColors()[1]
    }
    else{
        rowView.backgroundColor = NSColor.clear()
    }    
}

...添加后(及其由 TableView 配置的背景颜色)。

(顺便说一句,事实证明我根本不需要自定义行 View 。至少不需要自定义背景颜色)

关于cocoa - 如何在 Interface Builder 中构建 NSTableRowView 原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38952444/

相关文章:

ios - 在 Mac 上未收到自定义记录区的 CloudKit 推送通知

cocoa - 向菜单项添加操作

iphone - 如何在 Xcode 4 的 Interface Builder 的类 Pane 中定义 Outlets 和 Actions?

ios - Xcode 布局约束 : selecting divisions

objective-c - 在标准 NSWindow 上创建自定义标题栏

objective-c - 核心数据 : To-Many Relationship ordered upon restart

cocoa - 单击表外某处时取消选择 NSTableView

ios - 基础和 cocoa 框架之间的关系

ios - NSURLSessionDataTask : Application crashes in NSOperationQueue

objective-c - 什么是 "non-weak zeroing reference"