以编程方式将NSTableView添加到NSView

时间:2012-08-09 14:48:39

标签: cocoa nstableview nsview nstableviewcell nstablecolumn

我在以编程方式向NSView添加NSTableView时遇到了一些麻烦。该视图是NSSplitView的第一个视图。我的指针设置正确我确定它,因为我可以添加NSButton到视图没问题。我的tableview的委托和数据源方法也按预期工作。如果我使用界面构建器将表视图添加到我的视图,它就可以工作。但是,我不想使用IB。我希望能够通过代码来做到这一点。这是我目前使用的代码。

-(void)awakeFromNib{


    tableData = [[NSMutableArray alloc]initWithObjects:@"March",@"April",@"May", nil];


    tableView = [[NSTableView alloc]initWithFrame:firstView.frame];



    [tableView setDataSource:self];
    [tableView setDelegate:self];



    [firstView addSubview:tableView];

    NSButton *j = [[NSButton alloc]initWithFrame:firstView.frame];
    [j setTitle:@"help"];

    [firstView addSubview:j];




}

NSButton对象出现在屏幕上,但如果我注释掉按钮,则表格视图不会出现。我究竟做错了什么。谢谢您的帮助。

2 个答案:

答案 0 :(得分:4)

谢谢你,在你的帮助下,我能够弄清楚这一点。 IB会自动在表视图周围插入NSScrollview,它还会为您插入一列。为了从代码中执行此操作,您需要分配滚动视图和列。如果有其他人遇到这个问题,这就是我目前正在使用的内容。

-(void)awakeFromNib{

    tableData = [[NSMutableArray alloc]initWithObjects:@"March",@"April",@"May", nil];

    NSScrollView * tableContainer = [[NSScrollView alloc] initWithFrame:firstView.bounds];

    //This allows the view to be resized by the view holding it 
    [tableContainer setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];

    tableView = [[NSTableView alloc] initWithFrame:tableContainer.frame];
    [tableView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
    NSTableColumn *column =[[NSTableColumn alloc]initWithIdentifier:@"1"];
    [column.headerCell setTitle:@"Header Title"];


    [tableView addTableColumn:column];



    [tableView setDataSource:self];
    [tableView setDelegate:self];


    [tableContainer setDocumentView:tableView];

    [firstView addSubview:tableContainer];

    //You mentioned that ARC is turned off so You need to release these:
    [tableView release];
    [tableContainer release];
    [column release];


}

感谢您的帮助。

答案 1 :(得分:1)

默认情况下,

NSTableView位于NSScrollView。所以你可以这样做:

tableData = [[NSMutableArray alloc] initWithObjects:@"March",@"April",@"May", nil];

NSScrollView * tableContainer = [[NSScrollView alloc] initWithFrame:firstView.frame];
tableView = [[NSTableView alloc] initWithFrame:firstView.frame];

[tableView setDataSource:self];
[tableView setDelegate:self];

[tableContainer setDocumentView:tableView];

[firstView addSubview:tableContainer];

//You mentioned that ARC is turned off so You need to release these:
[tableView release];
[tableContainer release];
相关问题