Cocoa Programming for Mac OS X: Custom Views
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 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:
- The content view of a window.
- NSBox. The contents of a box are its subviews.
- 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.
NSSplitView. Each view in a split view is a subview (Figure 17.2).
Figure 17.2 A Scroll View in a Split View
NSTabView. As the user chooses different tabs, different subviews are swapped in and out (Figure 17.3).
Figure 17.3 A Tab View