Chapter 7. Custom Views
Cocoa’s default set of
controls covers most common UI needs, but it can’t
cover everything. For example, you might want to create a drawing
application and need a view that can have lines and other shapes
drawn into it. Or, you might want to create a custom graph of stock
data over time. Whenever you have these kind of needs, you will need
to create a subclass of
NSView
: a custom view.
A custom view is responsible for drawing content into, and handling events that occur within, its bounds —the rectangular region given to it by its superview. You can use any of Cocoa’s drawing tools to draw content into the view. In this chapter, we’ll work through a couple of basic custom-view examples to show you how everything works. Then, in the next chapter, you’ll build on what you learn in this chapter to create a custom view to respond to user events.
Custom View Creation Steps
When you make a custom subclass of
NSView
and want to perform custom drawing and
handle events, the following procedure applies:
In Interface Builder, define a subclass of
NSView
, then generate header and implementation files.Drag a Custom View object from the Views palette onto a window, and resize it.
With the Custom View object still selected, choose the Custom Class panel of the Info window, and select the custom class. Connect any outlets and actions.
If needed, override the designated initializer (
initWithFrame:
) to perform any custom initialization.Implement the
drawRect:
method ...
Get Learning Cocoa with Objective-C, 2nd Edition 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.