cocoanstableviewnsviewnstableviewcellnstablecolumn

Adding NSTableView to NSView Programmatically


I am having a bit of trouble adding a NSTableView to an NSView programatically. The view is the first view of an NSSplitView. My Pointers are set up right i am sure of it because I can add a NSButton to the view no problem. Also my tableview's delegate and datasource methods are working as expected. If I use interface builder to add the table view to my view it works. However, I dont want to use IB. I would like to be able to do this through code. Here is the code I am currently using.

-(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];




}

The NSButton object appears on screen although if I comment out the button the tableview does not appear. What am I doing wrong. Thanks for the help.


Solution

  • Thank you, from your help I was able to figure this out. IB automatically inserts the NSScrollview around the table view and it also inserts a column for you. In order to do it this from code you need to allocate a scroll view and a column. Here is what I am currently utilizing if anyone else comes across this problem.

    -(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];
    
    
    }
    

    Thanks for your help.