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.
Launch Project Builder and choose PB’s File → New Project menu command.
Choose Application → Cocoa Application in the New Project Assistant and give your new project the name “ViewDemo”.
Double-click the
MainMenu.nibfile in the Resources group in the Groups & Files pane to launch IB and display theMainMenu.nibwindow.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.
Change the name of the new subclass from “MyView” to “BlackView”.
Choose Classes → Create Files for BlackView and insert the class files into the ViewDemo project.
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
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.
Drag a CustomView icon from IB’s Cocoa-Containers palette and drop it in the empty window.
Type Command-1 and then change the class of the custom NSView to BlackView in the NSView (Custom) Info window. See Figure 15-1.
Resize the ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access