Home > Articles > Programming > General Programming/Other Languages

Cocoa® Programming for Mac® OS X: Custom Views

  • Print
  • + Share This
Aaron Hillegass teaches you how to create a subclass of NSView. Even if you do not plan to do custom drawing or event handling, by learning how to create a new view class, you will learn a lot about how Cocoa works.
This sample chapter is excerpted from Cocoa® Programming for Mac® OS X, by Aaron Hillegass.
This chapter is from the book

This chapter is from the book

All the visible objects in an application are either windows or views. In this chapter, you will create a subclass of NSView. From time to time, you will create a custom view to do custom drawing or event handling. Even if you do not plan to do custom drawing or event handling, by learning how to create a new view class, you will learn a lot about how Cocoa works.

Windows are instances of the class NSWindow. Each window has a collection of views. Each view 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 12.1). The window has a content view that completely fills its interior. The content view usually has several subviews. Each subview may have subviews of its own. Every view knows its superview, its subviews, and the window it lives on.

Figure 12.1 Views Are in a Hierarchy

Here are the relevant methods:

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

Any view can have subviews, but most don't. Here are five views that commonly have subviews.

  • The content view of a window.

  • NSBox. The contents of a box are its subviews.

  • NSScrollView. If a view appears in a scroll view, it is a subview of the scroll view. The scroll bars are also subviews of the scroll view.

  • NSSplitView. Each view in a split view is a subview (Figure 12.2).

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

Figure 12.2 A Scroll View in a Split View

Figure 12.3 A Tab View

  • + Share This
  • 🔖 Save To Your Account