Draw NSStrings
As a very simple introduction to drawing, in this section you’ll create an application that renders a string into the upper-left corner of a custom NSView subclass:
Create a new Cocoa application project called Simple Draw.
Open the main nib file.
Create a subclass of NSView called
MyView.Create the files for MyView and add them to the project.
Make the application’s window a bit smaller and drag a custom view from the More Views palette to the window, as shown in Figure 1.11.

Figure A-11. Adding a custom view object to the interface
Select CustomView, bring up the Info window, and change the view’s class to MyView.
Open
MyView.hand add the following instance varibles and method declarations.These instance variables and setter methods allow the view to maintain a notion of the current string and the current font. Changing either will cause the view to redraw using the new object.
@interface MyView: NSView { NSString *string; NSFont *font; } - (void)setString:(NSString *)value; - (void)setFont:(NSFont *)value; - (BOOL)isFlipped; @endOpen
MyView.mand add theisFlippedmethod. This method flips the origin of the coordinate system to the upper-left corner of the view:- (BOOL)isFlipped { return YES; }Override the
initWithFrame:method to set the default string and font for the view:- (id)initWithFrame:(NSRect)frame { [super initWithFrame:frame]; [self setString: @"Hello World"]; ...
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