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.nib
file in the Resources group in the Groups & Files pane to launch IB and display theMainMenu.nib
window.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 ...
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.