Chapter 15. Drawing in a Rectangle: More Fun with Cocoa Views
In the previous chapter, we saw how to draw in an NSView using Quartz drawing commands. The purpose of this chapter is to learn more about NSView’s drawRect: method and Cocoa views in general. Recall that to us a view is any object that is a member of the NSView class or any of its subclasses (just as a responder is any object that is a member of the NSResponder class or any of its subclasses).
The Advantages of NSView’s drawRect: Method
As we saw in Chapter 14, the main advantage of the drawRect: method is that it localizes all of the drawing commands necessary to draw your NSView in a single method. In practice, this allows you to separate the code in your application that controls layout from the code that controls drawing. This leads to an application that is cleaner, easier to maintain, and, in many cases, more efficient.
The drawRect: method can be invoked under a variety of circumstances:
The NSView draws “itself” the first time that it is displayed in its window.
If the NSView’s window is not buffered, the NSView redraws itself every time the window is exposed.
If the NSView is displayed in an NSScrollView, it redraws part of itself whenever the user makes a new part of it visible by dragging the scrollbar.
If the user wants to print the NSView, the NSView’s drawRect: method is invoked to perform the appropriate Quartz calls for the given device.
If the user wants to save the contents of the NSView as a PDF ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access