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:

  1. Create a new Cocoa application project called Simple Draw.

  2. Open the main nib file.

  3. Create a subclass of NSView called MyView.

  4. Create the files for MyView and add them to the project.

  5. 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.

    Adding a custom view object to the interface

    Figure A-11. Adding a custom view object to the interface

  6. Select CustomView, bring up the Info window, and change the view’s class to MyView.

  7. Open MyView.h and 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;
    
    @end
  8. Open MyView.m and add the isFlipped method. This method flips the origin of the coordinate system to the upper-left corner of the view:

    - (BOOL)isFlipped 
    {
        return YES;
    }
  9. 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"]; ...

Get Learning Cocoa 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.