BlackView: An NSView That Paints Itself Black

In this chapter, we’ll play with a number of simple, trivial NSView subclasses to learn more about how drawRect: and Interface Builder work. The first view is BlackView, an NSView whose drawRect: method fills the NSView with black.

  1. Launch Project Builder and choose PB’s File New Project menu command.

  2. Choose Application Cocoa Application in the New Project Assistant and give your new project the name “ViewDemo”.

  3. Double-click the MainMenu.nib file in the Resources group in the Groups & Files pane to launch IB and display the MainMenu.nib window.

  4. Select the NSView class under the Classes tab of IB’s Nib File window and subclass NSView by choosing the Classes Subclass NSView menu command.

  5. Change the name of the new subclass from “MyView” to “BlackView”.

  6. Choose Classes Create Files for BlackView and insert the class files into the ViewDemo project.

  7. Back in PB, insert the drawRect: method shown here in bold into BlackView.m:

    #import "BlackView.h"
    @implementation BlackView
    - (void)drawRect:(NSRect)aRect
                         {
                           [ [NSColor blackColor] set];
                           [NSBezierPath fillRect:aRect];
                         }
    @end
  8. Back in IB, resize the empty window titled “Window” so it’s about three inches wide and one inch tall. The exact size isn’t important here.

  9. Drag a CustomView icon from IB’s Cocoa-Containers palette and drop it in the empty window.

  10. Type Command-1 and then change the class of the custom NSView to BlackView in the NSView (Custom) Info window. See Figure 15-1.

  11. Resize the ...

Get Building Cocoa Applications: A Step by Step Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.