Home > Articles > Home & Office Computing > Mac OS X

Cocoa Programming for Mac OS X: Custom Views

  • Print
  • + Share This
All visible objects in an application are either windows or views. In this chapter, Aaron Hillegass shows how to create a subclass of NSView. From time to time, you may need to create a custom view to do custom drawing or event handling. Even if you do not plan to do custom drawing or event handling, you will learn a lot about how Cocoa works by learning how to create a new view class.
This chapter is from the book

Windows are instances of the class NSWindow. Each window has a collection of views, each of which is responsible for a rectangle of the window. The view draws inside that rectangle and handles mouse events that occur there. A view may also handle keyboard events. You have worked with several subclasses of NSView already: NSButton, NSTextField, NSTableView, and NSColorWell are all views. (Note that a window is not a subclass of NSView.)

The View Hierarchy

Views are arranged in a hierarchy (Figure 17.1). The window has a content view that completely fills its interior. The content view usually has several subviews, each of which may have subviews of its own. Every view knows its superview, its subviews, and the window it lives on.

Figure 17.1

Figure 17.1 Views Hierarchy

Here are the relevant methods from NSView:

    - (NSView *)superview;
    - (NSArray *)subviews;
    - (NSWindow *)window;

Any view can have subviews, but most don't. The following five views commonly have subviews:

  1. The content view of a window.
  2. NSBox. The contents of a box are its subviews.
  3. NSScrollView. A view that appears in a scroll view is a subview of the scroll view. The scroll bars are also subviews of the scroll view.
  4. NSSplitView. Each view in a split view is a subview (Figure 17.2).
    Figure 17.2

    Figure 17.2 A Scroll View in a Split View

  5. NSTabView. As the user chooses different tabs, different subviews are swapped in and out (Figure 17.3).
    Figure 17.3

    Figure 17.3 A Tab View

  • + Share This
  • 🔖 Save To Your Account