在 NSTableView 中创建自定义单元格

Create a custom cell in a NSTableView

在我的应用程序中,我正在尝试创建一个自定义单元格,如下所示:

我知道如何用 iOS 做到这一点,我想它应该与使用 OS X 完全相同。 所以在界面生成器中,我设计了 table 视图,但我可以想出如何创建自定义单元格。我尝试在我设计 table 视图的 .xib 中插入我需要的自定义组件(2 NSTextField 和 2 NSImageView),然后我创建一个 class "CustomCell.m""CustomCell.h" 作为 NSTableCellView 的子 class,所以我试图将我的组件连接到这个 class,但我无法添加它...为什么我无法将组件连接到“CustomCell”class?怎么了?你能帮我找到一个方法来做到这一点吗(也许还有教程)?

为此,我只是按照现在的方法为 iOS

创建自定义 table 单元格

在您的 xib 中,select 您要连接的自定义单元格,然后转到右侧面板实用程序区域中的身份检查器 (https://developer.apple.com/library/ios/recipes/xcode_help-general/Chapters/AbouttheUtilityArea.html)。将 class 更改为 CustomCell 类型。然后你应该能够将它连接到插座

从 Lion 开始,Apple 不鼓励使用 NSCell 子类。你现在可以做一个基于 NSView 的 NSTableView,这样就灵活多了。

我已经通过在 dataSource 方法中创建 NSView 来完成它们,但是 here's 使用 nib 完成它的一个不错的教程。

也见 apple docs

  1. 在 Xib 中,添加一个 NSTableView 并确保 contentType 在 Attributes Inspector 窗格中是 View Based。
  2. Table列包含一个TableCellview,默认包含一个TableViewCell。删除 TableViewCell。
  3. 根据需要将 NSTextFields 和 ImageView 拖到 TableCellview 中。 默认情况下,NSTableCellview 支持 1 个 Imageview 和 1 个 Textfield。如果每个都需要两个,请继承 NSTableCellview 并为您的组件创建 IBOutlet 属性,并将 IB 中 NSTableCellview 的 class 更改为 InheritedTableCellview。

    @interface InheritedTableCellview : NSTableCellView
    
    @property (assign) IBOutlet NSTextField *secondTextField;
    @property (assign) IBOutlet NSImageView *secondImageView;
    
    @end
    
    @implementation SRITableCellView
    
    @end
    
  4. 用唯一的字符串命名 TableCellview 的标识符。

  5. 将 Imageview 和 Textfield 插座组件连接到 TableCellview。
  6. 连接表视图数据源并委托给 viewController。

在视图控制器中,实现以下数据源方法以显示所需的行数。

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView {
    return self.tableArray.count;
}

实现委托方法为每一行设置图像和文本,

- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row
{
    InheritedTableCellview *cellView = [tableView makeViewWithIdentifier:@"MainCell" owner:self];
    cellView.backgroundStyle = NSBackgroundStyleDark;
    cellView.textField.stringValue = self.tableArray[row][@"textValue1"];
    cellView.imageView.image = [NSImage imageNamed:self.tableArray[row][@"image1"]];
    cellView.secondTextField.stringValue = self.tableArray[row][@"textValue2"];
    cellView.secondImageView.image = [NSImage imageNamed:self.tableArray[row][@"image2"]];

    return cellView;
}