Search code examples
objective-ccocoansscrollview

Create NSScrollView Programmatically in an NSView - Cocoa


I have an NSView class which takes care of a Custom View created in the nib file.

Now I want to add an NSScrollView to the custom view, but I need to do it programmatically and not using Interface Builder (Embed Into Scroll View).

I have found this code:

NSView *windowContentView = [mainWindow contentView];
NSRect windowContentBounds = [windowContentView bounds];
scrollView = [[NSScrollView alloc] init];
[scrollView setBorderType:NSNoBorder];
[scrollView setHasVerticalScroller:YES];
[scrollView setBounds: windowContentBounds];
[windowContentView addSubview:scrollView];

Assuming I declare as IBOutlets the variables 'mainWindow' and 'scrollView' above, how would I go about connecting them to the proper components in Interface Builder? Does it make any sense to do it this way?

Or is there a better way to add a scroll view programmatically?

P.S. I cannot connect them in the usual way because I cannot create an NSObject Object from Interface Builder, or use the File Owner..


Solution

  • This code fragment should demonstrate how to create an NSScrollView programmatically and use it to display any view, whether from a nib or from code. In the case of a nib generated view, you simply need to load the nib file to your custom view prior, and have an outlet to your custom view (outletToCustomViewLoadedFromNib) made to File's Owner.

    NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:[[mainWindow contentView] frame]];
    
    // configure the scroll view
    [scrollView setBorderType:NSNoBorder];
    [scrollView setHasVerticalScroller:YES];
    
    // embed your custom view in the scroll view
    [scrollView setDocumentView:outletToCustomViewLoadedFromNib];
    
    // set the scroll view as the content view of your window
    [mainWindow setContentView:scrollView];
    

    Apple has a guide on the subject, which I won't link to as it requires Apple Developer Connection access and their links frequently break. It is titled "Creating and Configuring a Scroll View" and can currently be found by searching for its title using Google.