macoscocoaappkit

How to display sheet view in NSWindow


How do I implement the view in following image.
The view which appears when + button is clicked in System Preferences > Network enter image description here


I have following questions:

  1. Does this view system has a specific name (like popover), because I have seen it in many places in Mac.
  2. How to implement it in IB ?
  3. Can this be done in a popover window instead of NSWindow ?(or is it only possible in NSWindow like toolbar)

Solution

  • In Cocoa these are called sheets. Take a look at the sheet programming guide, however, this is terribly out of date!

    You need to call -beginSheet:completionHandler: on the window you want to display the sheet. If you have single-window application you can ask the AppDelegate for the window and launch the sheet like so,

    // This code should be in AppDelegate which implement the -window method
    NSWindow *targetWindow = [self window]; // the window to which you want to attach the sheet
    NSWindow *sheetWindow = self.sheetWindowController.window // the window you want to display at a sheet
    
    // Now start-up the sheet
    [targetWindow beginSheet:sheetWindow completionHandler:^(NSModalResponse returnCode) {
    
            switch (returnCode) {
    
                case NSModalResponseCancel:
                    NSLog(@"%@", @"NSModalResponseCancel");
                    break;
    
                case NSModalResponseOK:
                    NSLog(@"%@", @"NSModalResponseOK");
                    break;
    
                default:
                    break;
            }
        }];
    

    You will notice that when the sheet completes it will return a certain modal response --- we will return to this point in a shortly.

    Next you need to implement the content that you want to display in the sheet; this must be done in an NSWindow. I find it much easier to use a NSWindowController and implement the window in a separate XIB file. For example, see below,

    NSWindow containing a items to be displayed in the sheet.

    Now you need to implement the code in your custom NSWindowController (or plain NSWindow if you are old-school and love to manage your own NIB loading) which will issue the correct modal response. Here I have hooked up the cancel and OK buttons to the following actions methods,

    - (IBAction)cancelButtonAction:(id)sender {
        [[[self window] sheetParent] endSheet:self.window returnCode:NSModalResponseCancel];
    }
    
    - (IBAction)OKButtonAction:(id)sender {
        [[[self window] sheetParent] endSheet:self.window returnCode:NSModalResponseOK];
    }
    

    The model response will get sent to your completion handler block.

    Sample project on github.