以编程方式将 NSTableView 添加到 NSView

xMy*_*icx 1 cocoa nsview nstableview nstablecolumn nstableviewcell

我在以编程方式将 NSTableView 添加到 NSView 时遇到了一些麻烦。该视图是 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];




}
Run Code Online (Sandbox Code Playgroud)

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

xMy*_*icx 5

谢谢你,在你的帮助下,我能够解决这个问题。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];


}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助。