Inherits from: NSResponder : NSObject
Conforms to: NSCoding
(NSResponder)
NSObject (NSObject)
Declared in: AppKit/NSView.h
frame | Returns the NSView's location and size. |
bounds | Returns the NSView's internal origin and size. |
setNeedsDisplay: | Marks the NSView as needing to be redrawn. |
window | Returns the NSWindow that contains the NSView. |
drawRect | Draws the NSView. (All subclasses must implement this method, but it's rarely invoked explicitly.) |
NSView is an abstract class that provides concrete subclasses with a structure for drawing, printing, and handling events. NSViews are arranged within an NSWindow, in a nested hierarchy of subviews. A view object claims a rectangular region of its enclosing superview, is responsible for all drawing within that region, and is eligible to receive mouse events occurring in it as well. In addition to these major responsibilities, NSView handles dragging of icons and works with the NSScrollView class to support efficient scrolling. The following sections explore these areas and more.
Most of the functionality of NSView is either automatically invoked by the Application Kit, or is available in Interface Builder. Unless you're implementing a concrete subclass of NSView or working intimately with the content of the view hierarchy at run time, you don't need to know much about this class's interface. See Commonly Used Methods above for methods you might use regardless.
To be displayed, an NSView must be placed in an NSWindow. All view objects within an NSWindow are arranged in a hierarchy that begins at the NSWindow's content view, with each NSView having a single superview and zero or more subviews (see the NSWindow class specification for more on the content view). An NSView's superview and all the NSViews above the superview are sometimes referred to as the NSView's ancestors. An NSView's subviews and all of their subviews on down are known as the NSView's descendants. Each NSView in the view hierarchy has its own area to draw in and its own coordinate system, expressed as a transformation of its superview's coordinate system. An NSView can scale, translate, or rotate its coordinates dynamically, and a subclass can declare its y axis flipped to allow drawing from top to bottom-useful for drawing text, for example.
Graphically, an NSView can be regarded as a framed canvas. The frame locates the NSView in its superview, defines its size, and clips drawing to its edges, while the canvas defines the NSView's own internal coordinate system and hosts the actual drawing. The frame can be moved around, resized, and rotated in the superview, so that the NSView's image moves with it. Similarly, the canvas can be shifted, stretched, and rotated, so that the drawn image moves within the frame. The frame maps onto a region of the canvas that defines the bounds of what can possibly be seen. An NSView therefore keeps track of its space using two rectangles, one for each perspective: The frame rectangle gives the exterior perspective and the bounds rectangle give the interior. The frame and bounds methods, respectively, return these rectangles. This figure shows the relation between the frame rectangle, on the left, and the bounds rectangle over the canvas, on the right:
Although the bounds rectangle indicates the portion of the NSView that is potentially visible through the frame, if the frame runs outside of the superview the image will be clipped even within the bounds rectangle. An NSView's visible rectangle reflects the portion of an NSView that actually displays, in terms of its own coordinate system (the darker gray rectangle in the figure below). It isn't often important to know what the visible rectangle is, since the display mechanism automatically limits drawing to visible portions of a view. If a subclass must perform expensive precalculation to build its image, though, it can use the visibleRect method to limit its work to what's actually needed.
The constructor establishes an NSView's frame rectangle, but doesn't insert it into an NSWindow's view hierarchy. This is the job of the addSubview: method, which you send to the NSView that you want to contain the newly initialized one. The frame rectangle is then interpreted in terms of the superview, properly locating the new NSView both by its place in the view hierarchy and its location in the superview's NSWindow.
After initialization, you can move an NSView programmatically using any of the frame-setting methods: setFrame, setFrameOrigin, setFrameSize, and setFrameRotation. When you move an NSView all of its subviews move along with it. When you change the frame rectangle's size, the bounds rectangle is automatically resized to match (see figure below), and the subviews are automatically resized as described in Moving and Resizing NSViews below. setFrameRotation rotates the NSView around the origin of the frame rectangle (which is typically the lower left corner).
A number of methods access the view hierarchy itself. superview returns the receiver's containing NSView, while subviews returns an NSArray containing its immediate descendant NSViews. The window method returns the NSWindow whose view hierarchy the receiver belongs to. You can add NSViews to and remove them from the view hierarchy using the methods addSubview:, removeFromSuperview, and replaceSubview. An additional method, , allows you to specify the ordering of NSViews that may overlap (though laying out NSViews so that they overlap isn't recommended).
When you add a subview with addSubview:, the receiver retains the view. When you remove a subview from a view hierarchy with removeFromSuperview, or replace it with replaceSubview, the view is released.
When an NSView is added as a subview of another view, it automatically invokes the viewWillMoveToSuperview and viewWillMoveToWindow methods. Concrete subclasses can override these methods, allowing an instance to query its new superview or NSWindow about relevant state and update itself accordingly. A few other methods allow you to inspect relationships among NSViews: isDescendantOf confirms the containment of the receiver, ancestorSharedWithView finds the common container of two NSViews, and opaqueAncestor returns the closest containing NSView that's guaranteed to draw every pixel in the receiver's frame (possible the receiver itself).
At various times, particularly when handling events, you need
to convert a rectangle or point from the coordinate system of one
NSView to another (typically a superview or subview). NSView defines
six methods that convert rectangles, points, and sizes in either
direction:
convertPointFromView | convertPointToView |
convertSizeFromView | convertSizeToView |
convertRectFromView | convertRectToView |
These methods convert geometric structures between the receiver's coordinate system and another NSView's within the same NSWindow, returning an alternate expression for the same on-screen location or area. Note that the structure in question needn't actually be located within the NSView's bounds rectangle; it's merely assumed to be expressed in that NSView's coordinate system. If the second argument to a conversion method is null, the conversion is made between the receiver's coordinate system and the base coordinate system of its NSWindow.
For converting to and from the screen coordinate system, NSWindow defines the convertBaseToScreen: and convertScreenToBase: methods. Using the NSView conversion methods along with these allows you to convert a geometric structure between an NSView's coordinate system and the screen's with only two messages.
Conversion is straightforward when neither NSView is rotated, or when dealing only with points. When converting rectangles or sizes between NSViews with different rotations, the geometric structure must be altered in a reasonable way. In converting a rectangle NSView makes the assumption that you want to guarantee coverage of the original screen area. To this end, the converted rectangle is enlarged so that when located in the appropriate NSView it completely covers the original rectangle (the left side of the figure below, with 15 degrees of rotation). In converting a size NSView simply treats it as a vector from (0.0, 0.0) and maps it onto the destination coordinate system. Though the length remains the same, the balance along the two axes shifts according to the rotation (the right side of the figure below, rotated 45 degrees).
Drawing in an NSView is as simple as implementing the drawRect method to generate the appropriate PostScript code for the image you want displayed-the display mechanism handles the rest of the work. On the other hand, it can be as complex as dealing with the PostScript language itself, the coordinate transformations from superview to subview, and the operation of the display mechanism. This section and The Display Mechanism progress from the basic to the esoteric, keeping the picture correct, if incomplete, at each stage.
In order for a concrete subclass of NSView to display any kind of image, it must implement the drawRect method. This method is invoked during the display process to generate PostScript code that's rendered by the Window Server into a raster image. drawRect takes a single argument, an NSRect describing the area that needs to be drawn in the receiver's own coordinate system.
Sometimes, an implementation of drawRect ignores the rectangle provided, drawing everything each time it's invoked. This isn't a problem for a simple image, but for complex drawing it can be an extremely inefficient practice. Sending drawing instructions and data to the Window Server has a cost, and it's best to minimize that cost where possible. You can do this by testing whether a particular graphic shape intersects the rectangle being drawn, using NSIntersectsRect() and similar functions.
As indicated in the example above, drawing can be performed by invoking PostScript client library functions (also known as single-operator functions), which map directly to PostScript operators. The Application Kit provides a few higher-level mechanisms for handing PostScript instructions to the Window Server. The first is the pswrap program, which converts custom PostScript procedures into C functions that you can call in the same manner as client library functions. Wrapping complex drawing procedures minimizes the overhead of communication with the Window Server by passing a group of instructions in one interprocess message, as opposed to a number of such messages for repeated single-operator calls. The Application Kit itself defines some pswrap functions, such as NSRectFill(), and you can define your own.
Describing the PostScript language, client libraries, and pswrap is
outside this scope of this class description. For more information,
see:PostScript Language Reference Manual, Second Edition.
Adobe Systems Incorporated. Addison Wesley, 1990. ISBN 0-201-18127-4.Descriptions
of OPENSTEP PostScript operators and client functions, accessible from
the Project Builder application in the Application Kit framework documentation.For
information on pswrap
,
contact Adobe Systems.
The second higher-level mechanism is provided by Application Kit classes that perform drawing within an NSView, such as NSImage and the various NSCell subclasses. These classes send PostScript instructions to the Window Server but don't have the overhead of maintaining a drawing context that NSView has. Objects that draw themselves are useful for encapsulating graphic elements that need to be drawn over and over, at different locations, or in slightly different ways. See the appropriate class specifications for more information on drawing with them.
Another way of drawing within an NSView is to add subviews that each do their own drawing. This is somewhat more heavyweight than using NSCells or NSImages, but the elements of such a constructed group have the full power of the NSView machinery at their disposal, including the autosizing of components and event handling, features described later in this class description.
Most of an NSView's displayed image is a stable representation of its state, and is defined in the device-independent PostScript language. View objects also interact dynamically with the user, however, and this interaction often involves drawing that isn't integral to the image itself-selections and other highlighting, for example. Such drawing should be performed only to the computer screen, and never to a printer or fax device, or to the pasteboard (as when drawing an EPS image). You can predicate drawing on this difference of output device by sending the current DPS context an isDrawingToScreen message.
By default, an NSView's coordinate system is based at (0.0, 0.0) in the lower-left corner of its bounds rectangle, its units are the same size as those of its superview, and its axes are parallel to those of its frame rectangle. To change this coordinate system you can alter the NSView's bounds rectangle, thereby placing the canvas inside the frame rectangle, or transform it directly using PostScript operators in the drawRect method. Changing the bounds rectangle sets up the basic coordinate system, with which all drawing performed by the NSView begins; concrete subclasses of NSView typically alter the bounds rectangle immediately as needed in their initWithFrame: methods (or other designated initializers). Direct transformations are useful for temporary effects, such as scaling one axis to draw an oval instead of a circle, then scaling it back before stroking the path to preserve line widths; rotating the axes to draw text at an angle; or repeatedly translating the origin to draw the same figure in several locations.
The basic method for changing the bounds rectangle is setBounds, which both positions and stretches the canvas. The origin of the rectangle provided to setBounds becomes the lower-left corner of the bounds rectangle, and the size of the rectangle is made to fit in the frame rectangle, effectively scaling the NSView's drawn image. In the figure below, the bounds rectangle from the previous example is moved and doubled in size; the result appears on the right:
You can also set the parts of the bounds rectangle independently, using setBoundsOrigin and setBoundsSize. An additional method, setBoundsRotation, rotates the coordinate system around its origin within the bounds rectangle (not the origin of the bounds rectangle itself). It also enlarges the visible rectangle to account for the rotation, so that it's expressed in the rotated coordinates yet completely covers the visible portion of the frame rectangle. This adds regions that must be drawn, yet will never be displayed (the triangular areas in the figure below). For this reason, rotating the bounds rectangle is strongly discouraged. It's better to rotate the coordinate system by using PostScript operators in the drawRect method rather than by rotating the bounds rectangle.
setBoundsOrigin, setBoundsSize, and setBoundsRotation all express their transformations in absolute terms. Another set of methods transform the coordinate system in relative terms; if you invoke them repeatedly, their effects accumulate. These methods are translateOriginToPoint:, scaleUnitSquareToSize, and rotateByAngle. See the individual method descriptions for more information.
One final type of coordinate transformation is statically
established by overriding the isFlipped method. NSView's implementation
returns false
, which means that the
origin of the coordinate system lies at the lower-left corner of
the default bounds rectangle and the y axis runs from bottom to
top. When a subclass overrides this method to return true
,
the NSView machinery automatically adjusts itself to assume that
the upper-left corner of the NSView holds the origin. In other words,
when isFlipped returns true
the
y axis runs from top to bottom. A flipped coordinate system affects
all drawing in the NSView itself and reckons the frame rectangles
of all immediate subviews from their upper-left corners, but it
doesn't affect the coordinate systems of those subviews or the drawing
performed by them.
A flipped coordinate system doesn't affect an NSView's
subviews, but the other coordinate transformations do. Translation
of the bounds rectangle from the coordinate system origin shifts
all subviews along with the rest of the NSView's image. Scaling
and rotation actually affect the drawing of the subviews, as their coordinate
systems inherit and build on these alterations. You can determine whether
an NSView's coordinate system is (or was ever) altered from the
base coordinate system of its window using two methods. isRotatedFromBase returns true
if
the receiver or any of its ancestors in the view hierarchy has ever been
rotated, whether of the frame or of the bounds rectangle. isRotatedOrScaledFromBase similarly
returns true
if the receiver or any
of its ancestors has ever been rotated or been scaled from the base
coordinate system's unit size. You can determine whether the NSView
has never been rotated by checking that isRotatedOrScaledFromBase returns true
while isRotatedFromBase returns false
.
Note that these methods only offer hints about the coordinate system.
Their purpose is to help optimize certain operations, not to reflect
the present state: Once an NSView is marked as having been rotated or
scaled, it remains so marked for its lifetime.
To get the actual amount of rotation, use the frameRotation and boundsRotation methods. These return the rotation relative to the superview only, not to the base coordinate system, so if you want the latter amount you have to progress up through each superview to the NSWindow's content view, accumulating the rotation as you go. To get the scaling relative to the superview you can use convertSizeToView and examine the ratio of the original size to that of the superview. To get the scaling relative to the base coordinate system, use null as the second argument. This causes convertSizeToView to convert to the NSWindow's base coordinate system.
Displaying an NSView centers around the drawRect method, which transmits drawing instructions to the Window Server. Before this can happen, however, a number of other things must be established. First, of course, is the rectangle in the view that needs to be drawn. Once this is known, the view must be checked for opacity; if the view is partially transparent, its nearest opaque ancestor must be found and drawing must commence from there. Once all of this is determined and a particular view is to be drawn, the Window Server must know which window device the view is in, how to clip drawing to the appropriate region, and what coordinate system to use. This is all handled outside drawRect, by NSView's various display methods. The following sections examine each of these points in turn.
The most common way of causing an NSView to redisplay is to tell it that its image is invalid. On each pass through the event loop, all views that need to redisplay do so. NSView defines two methods for marking a view's image as invalid; setNeedsDisplay:, which invalidates the view's entire bounds rectangle, and setNeedsDisplayInRect:, which invalidates a portion of the view. The automatic display of views is controlled by their window; you can turn this behavior off using NSWindow's setAutodisplay: method. You should rarely need to do this however; the autodisplay mechanism is well-suited to most kinds of update and redisplay.
The autodisplay mechanism invokes various methods that actually do the work of displaying. You can also use these methods to force a view to redisplay itself immediately when necessary. display and displayRect are the counterparts to the methods mentioned above; both cause the receiver to redisplay itself regardless of whether it needs to or not. Two additional methods, displayIfNeeded and displayIfNeededInRect, redisplay invalidated rectangles in the receiver if it's been marked invalid with the methods above. The rectangles that actually get drawn are guaranteed to be at least those marked as invalid, but the view may coalesce them into larger rectangles to save multiple invocations of drawRect.
NSViews don't necessarily cover every bit of their frames
with drawing. Because of this, the display methods must be sure
to find an opaque background behind the view that's ostensibly
being drawn, and begin displaying from there forward. The display
methods above all pull back up the view hierarchy to the first view that
responds true
to an isOpaque message,
bringing the invalidated rectangles along. NSView by default responds false
to isOpaque, so it's important
to remember to override this method to return true
if
appropriate when defining a subclass. Most Application Kit subclasses
of NSView actually do this.
If you want to exclude background views from drawing when forcing display to occur unconditionally, you can use NSView methods that explicitly omit backing up to an opaque ancestor. These methods, parallel to those mentioned above, are displayRectIgnoringOpacity:, displayIfNeededIgnoringOpacity, and displayIfNeededInRectIgnoringOpacity.
Before a display... method invokes drawRect, it sets the Window Server up with information about the view, including the window device it draws in, the coordinate system and clipping path it uses, and other PostScript graphics state (discussed in detail below, under PostScript Graphics State Objects). The method used to do this is lockFocus, and it has a companion method that undoes its effects, called unlockFocus.
All drawing code invoked by an NSView must be bracketed by invocations of these methods to produce proper results. If you define some methods that need to draw in a view without going through the display methods above, for example, you must send lockFocus to the view that you're drawing in before sending commands to the Window Server, and unlockFocus as soon as you are done.
It's perfectly reasonable to lock the PostScript focus on one view when another already has it. In fact, this is exactly what happens when subviews are drawn in their superview. The focusing machinery keeps a stack of which views have been focused, so that when one view is sent an unlockFocus message, the PostScript focus is restored to the view that was focused immediately before.
When an NSView receives a lockFocus message, its basic drawing
environment state is constructed and sent to the Window Server as
a PostScript graphics state object, or gstate
(this
is a PostScript user object, not a Java object). The basic state includes
default values for parameters that don't change often, but leaves
many other parameters undefined:
Parameter | Default Value |
coordinate transformation | The NSView's coordinate system as established by the bounds rectangle |
position | No default value, must be set before drawing |
path | No default value |
clipping path | As established by lockFocus |
font | No default value, must be set before drawing text |
line width | 0.0 |
line cap | 0 (a square butt end) |
line join | 0 (mitered joins) |
halftone screen | A device-dependent, type 3 halftone dictionary |
halftone phase | 0,0 |
flatness | 1.0 |
miter limit | 10 |
dash pattern | A normal solid line |
device | The current window |
stroke adjust | true |
color | No guaranteed default value |
color space | No guaranteed default value, varies with color |
color rendering | Calibrated RGB rendering |
overprint | false |
black generation | No default value |
transfer | No default value |
undercolor removal | No default value |
alpha (opacity) | 1.0 (opaque) |
instance drawing mode | false |
When drawing in an NSView, you must be sure to explicitly set relevant parameters that have no default value, or a PostScript error will result. Further, although drawing methods are free to set any gstate parameter, they should always restore the parameters to their original values when finished. This protects multiple drawing methods, and objects that draw within an NSView, such as NSImages and NSCells, from altering each other's graphics states. You can protect the gstate by bracketing the changes with PSgsave() and PSgrestore(), or by explicitly placing the parameter in question on the stack and resetting it later-for example, saving the line width only using PScurrentlinewidth(), performing your drawing, then calling PSsetlinewidth() to restore the prior value.
Normally the graphics state object is reconstructed from scratch each time the NSView is focused. You can instruct an NSView to keep a graphics state object indefinitely by sending it an allocateGState message (typically in the initialization method for a concrete subclass). This eliminates the overhead of continual reconstruction of the graphics state, and also allows you to omit commands for setting parameters from your drawing code. However, because a graphics state object does consume a fair amount of memory, you should be sure to test your application's performance with and without it. Persistent gstate objects are most suitable for NSViews that must be redrawn frequently with the same parameters.
When you set an NSView to use a persistent gstate object, it doesn't actually allocate one until it needs it. When it does create the graphics state object, the NSView invokes its setUpGState method to set the parameters. Your subclass can override this method to establish the parameters that you want kept in the graphics state. Your version of setUpGState can use methods such as the set method found in NSColor and NSFont, as well as client library functions such as PSsetlinewidth(), PSsetdash(), and so on.
You can cause an NSView to discard its gstate object by sending it a releaseGState message, or cause the view simply to invalidate its gstate object by sending a renewGState message. The latter method causes the NSView to reestablish its gstate parameters by invoking setUpGState the next time it's needed. Finally, if for some reason you need to access the persistent gstate object directly, the gState method returns its PostScript user object identifier.Although applications rarely need to use this value, it can be passed to the few PostScript operators that take an object identifier as a parameter, such as PScomposite and PSdissolve.
Repositioning an NSView is a potentially complex operation. Moving or resizing can expose portions of the NSView's superview that weren't previously visible, requiring the superview to redisplay. Resizing can also affect the layout of an NSView's subviews. Changes to an NSView's layout in any case may be of interest to other objects, which might need to be notified of the change. The following sections explore each of these areas.
None of the methods that alter an NSView's frame rectangle redisplays the NSView or marks it as needing display. When using the setFrame... methods, then, you must mark both the view being repositioned and its superview as needing display. This can be as simple as marking the superview in its entirety as needing display, or better, marking the superview in the old frame of the repositioned view and the view itself in its entirety.
The NSView class provides a mechanism to notify interested objects when a view object's frame rectangle is changed or its bounds rectangle is changed. The setFrame... methods post an NSViewFrameDidChangeNotification to the default notification center, unless the setPostsFrameChangedNotifications method has been used to turn notification off. The setBounds... methods post an NSViewBoundsDidChangeNotification to the default notification center, unless the setPostsBoundsChangedNotifications method has been used to turn notification off. Your application can use these notifications to perform special handling when a view object is moved or resized.
When an NSView's frame size changes, the layout of its subviews must often be adjusted to fit in the new size. NSView defines a mechanism that automates this process, allowing you to specify how any NSView should reposition itself when its superview is resized. Interface Builder allows you to set these attributes graphically with its Size Inspector, and in test mode you can examine the effects of autoresizing. You can also set autoresizing attributes programmatically using setAutoresizingMask with a mask containing any of the constants illustrated below, combined using the bitwise OR operator:
When one of these mask flags is omitted, the NSView's layout
is fixed in that aspect; when it's included the NSView's layout
is flexible in that aspect. For example, to keep an NSView in the
lower left corner of its superview, you specify NSViewMaxXMargin
| NSViewMaxYMargin
.
When more than one aspect along an axis is made flexible, the resize
amount is distributed evenly among them.
Autoresizing is on by default, but you can turn it off using the setAutoresizesSubviews method. Note that when you turn off an NSView's autoresizing, all of its descendants are likewise shielded from changes in the superview. Changes to subviews, however, can still percolate downward. Similarly, if a subview has no autoresize mask, it won't change in size, and therefore none of its subview will autoresize.
Autoresizing is accomplished using two methods. resizeSubviewsWithOldSize is invoked automatically by an NSView whenever its frame size changes. This method then simply sends a resizeWithOldSuperviewSize message to each subview. Each subview compares the old frame size to the new size and adjusts its position and size according to its autoresize mask. Subclasses of NSView can override either method to alter their autoresizing behavior.
Two cautions apply to autoresizing. First, it doesn't work at all in NSViews that have been rotated. Subviews that have been rotated can autoresize within a nonaltered superview, but then their descendants aren't autoresized. Also, for autoresizing to work correctly, the subview being autoresized must lie completely within its superview's frame. Apart from these limitations, autoresizing covers most layout changes quite well.
Beyond resizing its subviews, an NSView broadcasts notifications to interested observers any time its bounds and frame rectangles change. The notification names are NSViewFrameDidChangeNotification and NSBoundsDidChangeNotification, respectively. An NSView that bases its own display on the layout of its subviews, for example, can register itself as an observer for those subviews and update itself any time they're moved or resized. NSScrollView and NSClipView cooperate in this manner to adjust the NSScrollView's NSScrollers. You can turn notifications on and off using setPostsFrameChangedNotifications and setPostsBoundsChangedNotifications.
NSViews are the most typical receivers of event and action
messages, as described in the NSResponder and NSEvent class specifications.
An NSView subclass can handle any event or action message simply
by implementing it (being sure to invoke super
's
implementation as needed). Then, if an instance of that class is
the first in the responder chain to respond to that message, it
receives such messages as they're generated.
Except for an NSWindow's content view, an NSView's next responder is always its superview-most of the responder chain, in fact, comprises the NSViews from an NSWindow's first responder up to its content view. NSView addSubview: method automatically sets the receiver as the new subview's superview; you should never send setNextResponder: to an NSView object. You can safely add responders to the top end of an NSWindow's responder chain-the NSWindow itself if it has no delegate, or the delegate if it does.
As the class that handles display, NSView is the typical recipient of mouse and keyboard events. Mouse clicks, drags, and movements usually occur in some NSView or other, and most keystrokes represent text to be added for display at some point in a window. A mouse event starts at the lowest NSView containing it in the view hierarchy (or, the topmost NSView displayed under the cursor), and proceeds up the responder chain through superviews until some object handles it. Mouse Events below covers the details of handling mouse events. Most keyboard events start at the first responder, whatever it might be, and are similarly offered up the responder chain. Some actually change the first responder, thus allowing the user to perform many actions without using the mouse. See the NSResponder class specification for information on keyboard events. Tracking-rectangle events are monitored by the NSWindow and dispatched directly to the object that owns the tracking rectangle. Tracking Rectangles and Cursor Rectangles describes how to set up and handle these. An additional section covers the use of context-sensitive pop-up menus by your views.
An NSView can receive mouse events of three general types: clicks, drags, and movements. A custom subclass of NSView can interpret a mouse event as a cue to perform a certain action, such as sending a target-action message, selecting a graphic element, and so on. NSViews automatically receive mouse-clicked and mouse-dragged events, but because mouse-moved events occur so often and can bog down the event queue, an NSView must explicitly request its NSWindow to watch for them using NSWindow's setAcceptsMouseMovedEvents: method. Tracking rectangles, described below, are a less expensive way of following the mouse's location.
The NSView selected to receive a mouse event is determined by the NSWindow using NSView's hitTest method, which returns the lowest descendant that contains the cursor location of the event (this is also the topmost NSView displayed). Once the recipient is determined, the NSWindow sends it a mouseDown: message, which includes an NSEvent object containing information about the click. NSEvent's locationInWindow locates the cursor's hot spot in the coordinate system of the receiver's NSWindow. To convert it to the NSView's coordinate system, use convertPointFromView with a null NSView argument. From here, you can use isMouseInRect to determine whether the click occurred in an interesting area.
One of the earliest things to consider in handling mouse-down
events is whether the receiving NSView should become the first responder,
which means that it will be the first candidate for subsequent key
events and action messages. NSViews that handle graphic elements
that the user can select-drawing shapes or text, for example-should
typically accept first responder status on a mouse-down event, by
overriding the acceptsFirstResponder method
to return true
. This results in the
window making the receiving NSView first responder with NSWindow's makeFirstResponder: method.
Some NSViews, however, may not wish to change the selection upon
the first mouse click in a non-key window, which should normally
only order the window to the front. NSView's acceptsFirstMouse method controls
whether an initial mouse click is sent to the NSView or not. By default
it returns false
, which in most cases
is appropriate behavior. Certain subclasses, such as controls that
don't affect the selection, override this method to return true
.
Once an NSView has accepted a mouse event and determined its location, it can also check which mouse button was clicked and how many times. NSEvent's type method distinguishes between left and right mouse events, and the NSView can base its behavior on this information. Right mouse events are defined by the Application Kit to open pop-up menus, but you can override this behavior if necessary. NSEvent's clickCount method returns a number identifying the mouse event as a single-, double-, or triple-click (and so on).
NSViews that handle mouse clicks as a single event, from mouse down, through dragging, to mouse up, must usually short-circuit the application's normal event loop, entering a modal event loop to catch and process only events of interest. For example, an NSButton highlights upon a mouse-down event, then follows the mouse location during dragging, highlighting when the mouse is inside and unhighlighting when the mouse is outside. If the mouse is inside on the mouse-up event, the NSButton sends its action message.
A modal event loop is driven only as long as the user actually
moves the mouse. It won't work, for example, to cause continual
scrolling if the user presses the mouse button but never moves the
mouse itself. For this, your modal loop should start a periodic
event stream using NSEvent's class method startPeriodicEventsAfterDelay:withPeriod:,
and add PeriodicMask
to the mask
passed to nextEventMatchingMask:. In the switch() statement
the NSView can then check for a case of NSPeriodic and take whatever
action it needs to; scrolling a document view or moving a step in
an animation, for example. If you need to check the mouse location
during a periodic event, you can use NSWindow's mouseLocationOutsideOfEventStream method.
One special type of event is that for tracking mouse movement into and out of a region in the NSView. Such a region is known as a tracking rectangle; it triggers mouse-entered events when the cursor enters it and mouse-exited events when the cursor leaves it. This can be useful for displaying context-sensitive messages or highlighting graphic elements under the cursor, for example. An NSView can have any number of tracking rectangles, which can overlap or be nested one within the other; the NSEvent objects generated for tracking events include a tag that identifies the rectangle that triggered the event.
To create a tracking rectangle, use the addTrackingRect:owner:userData:assumeInside: method. This method registers an owner for the tracking rectangle provided, so that the owner receives the event messages. This is typically the NSView itself, but need not be. The method returns the tracking rectangle's tag so that you can store it for later reference in the event handling methods, mouseEntered: and mouseExited:. To remove a tracking rectangle, use the removeTrackingRect method, which takes as an argument the tag of the tracking rectangle to remove.
Tracking rectangles, though created and used by NSViews, are actually maintained by NSWindows. Because of this, a tracking rectangle is a static entity; it doesn't move or change its size when the NSView does. If you use tracking rectangles, you should be sure to remove and reestablish them any time you change the frame rectangle of the NSView that contains them. If you're using a custom subclass of NSView, you can override the frame- and bounds-setting methods to do this. You can also register an observer for the NSViewFrameDidChangeNotification (described below), and have it reestablish the tracking rectangles on receiving the notification.
One common use of tracking rectangles is to change the cursor image over different types of graphic elements. Text, for example, typically requires an I-beam cursor. Changing the cursor is such a common operation that NSView defines several convenience methods to ease the process. A tracking rectangle generated by these methods is called a cursor rectangle. The Application Kit itself assumes ownership of cursor rectangles, so that when the user moves the mouse over the rectangle the cursor automatically changes to the appropriate image. Unlike general tracking rectangles, cursor rectangles may not partially overlap. They may, however, be completely nested, one within the other.
Because cursor rectangles need to be reset often as the NSView's size and graphic elements change, NSView defines a single method, resetCursorRects, that's invoked any time its cursor rectangles need to be reestablished. A concrete subclass overrides this method, invoking addCursorRect for each cursor rectangle it wishes to set. Thereafter, the NSView's cursor rectangles can be rebuilt by invoking NSWindow's invalidateCursorRectsForView: method. If you find you need to temporarily remove a single cursor rectangle, you can do this with removeCursorRect. Be aware that resetCursorRects will reestablish that rectangle, unless you implement it to do otherwise.
An NSView's cursor rectangles are automatically reset whenever:
You can temporarily disable all the cursor rectangles in a window using NSWindow's disableCursorRects method or enable them with the enableCursorRects method. NSWindow's areCursorRectsEnabled method tells you whether they're currently enabled.
On Microsoft Windows, any view can be assigned a pop-up menu that's displayed when the user clicks the right mouse button over the view. setMenu: assigns an NSMenu to a view, and menu returns it. Your subclass can define a menu that's used for all instances by implementing the defaultMenu class method. It can also change the menu displayed based on the mouse event by overriding the menuForEvent instance method. This allows the view clicked to display different menus based on the location of the mouse and of the view's state, or to change or enable individual menu items based on the commands available for the view or for that region of the view. See the NSMenu and NSMenuItem class and protocol specifications for more information on using menus.
A tooltip is a bit of text that provides information about a view. If the user holds the cursor over the view for more than the default delay, the tooltip text is displayed in a small framed rectangle next to the cursor. By default, a view does not display a tooltip. To turn on tooltip display for a view, you invoke the setToolTip method to install tooltip text for the view. To turn display off, you invoke setToolTip with an empty string.
Printing or faxing an NSView uses the same PostScript description as for displaying on the screen, by simply changing the device. An NSView can check whether it's drawing to the screen in order to conditionally include or omit elements such as highlighting, but normally doesn't need to be involved with the PostScript generation process in a special way for printing. It may, however, need to take part in peripheral issues, including how it's divided into pages and placed on them, and generation of document structuring comments used by some PostScript document programs. The sections below cover these areas.
To print or fax an NSView, send it a print or fax message. You can also generate an EPS representation using either dataWithEPSInsideRect or writeEPSInsideRectToPasteboard. For any of these jobs, the NSView creates an NSPrintOperation object that manages the process of generating proper PostScript code for a printer or fax device. NSPageLayout, NSPrintInfo, and NSPrintPanel objects are also involved in the process. See those classes' specifications for more information on the printing process itself.
When an NSView is printed onto pages smaller than itself, it tiles itself out onto separate logical pages so that its entire visible region is printed. A subclass of NSView can alter the way pagination is performed by overriding two small sets of methods. The first set affects automatic pagination; the second replaces automatic pagination completely. One extra method allows the NSView to adjust the location of the printed image on the page. Finally, after pagination has actually been performed, the NSView is given the chance to draw additional marks on the page.
NSView's automatic pagination tries to fit as much of the view being printed onto a logical page, slicing the view into the largest possible chunks. This is sufficient for many views, but if a view's image must be divided only at certain places-between lines of text or cells in a table, for example, the view can adjust the automatic mechanism to accommodate this by reducing the height or width of each page. It does so by overriding up to four methods. provides an out parameter for the new bottom coordinate of the page, followed by the proposed top and bottom. An additional parameter limits the height of the page; the bottom can't be moved above it. works in the same way to allow the view to adjust the width of a page. The limits are calculated as a percentage of the proposed page's height or width. Your view subclass can also customize this percentage by overriding the methods heightAdjustLimit and widthAdjustLimit to return the reducible fraction of the page.
More complex views, such as those that display separate pages
over a background, need to direct their own pagination. An NSView
subclass that needs to do so overrides the knowsPagesFirst:last: method to return true
,
which signals that it will be calculating each page's dimensions,
and returns by reference its first and last page numbers.The pagination
machinery then uses these numbers, sending rectForPage to the NSView, which
uses the page number and the current printing information to calculate
an appropriate rectangle in its coordinate system. The adjustPage... methods
aren't used in this case.
The last stage of pagination involves placing the image to
be printed on the logical page. NSView's locationOfPrintRect places it according
to the NSPrintInfo's status. By default it places the image in
the upper left corner of the page, but if NSPrintInfo's isHorizontallyCentered or isVerticallyCentered methods return true
,
it centers a single-page image along the appropriate axis. A multiple-page
document, however, is always placed so that the divided pieces can be
assembled at their edges.
After the NSView has sliced out a rectangle and positioned it on a page, it's given two chances to add extra marks to the page, such as crop marks or fold lines. drawPageBorderWithSize is used for logical pages, and is invoked for each paginated portion of the view. drawSheetBorderWithSize is used for actual physical pages, or sheets, on which one or more logical pages may be laid out. In a 2-up printing, for example, the former method is invoked twice for each sheet, while the latter is invoked once for each sheet.
As an adjunct to the PostScript language itself, Adobe has defined a set of document structuring conventions that describe the internal structure of a given PostScript language document. NSView properly generates the basic information needed to structure its output, and defines a number of methods that subclasses can override to provide additional information. This section only describes the methods that relate to the structure of a conforming PostScript language document; see the individual method descriptions and Adobe's PostScript Language Reference Manual, Appendix G for more information.
An NSView subclass can override any of the methods that write
out document structuring comments and definitions. When overriding begin... or add... methods,
be sure to invoke super
's
implementation before writing additional information; when overriding end... methods,
invoke super
's implementation last.
The initial portion of a conforming PostScript language document is called the prologue, and contains two parts itself: the header and a set of procedure definitions. NSView's beginPrologue writes out the very beginning of the document. endHeaderComments closes the first part of the prologue. Subclasses can add their own procedure definitions to the end of the prologue by overriding endPrologue.
After the prologue comes the script, which contains a section that applies to the entire document, followed by sections for each page, and finally the document trailer. beginSetup and endSetup write the document setup section. Each page is written with five methods, in addition to drawRect. beginPage writes out the beginning of each page's document structuring comments. It's followed by beginPageSetup, which starts the page setup section. An additional method, addToPageSetup, does nothing by default, but allows subclasses to append extra procedure definitions and comments to the page setup. The page setup concludes with an endPageSetup message. After all this, endPage wraps up the page description; subclasses can override this method to add document structuring comments and PostScript code to the page trailer. The document trailer is written by the beginTrailer and endTrailer methods.
While an NSView is printing, its connection to the Window Server is replaced by a connection to the print job output. Sometimes the NSView needs to communicate briefly with the Window Server while printing; for example, it may need to read some data stored only on the Window Server, or open an attention panel to alert the user of a problem. In these cases, it can temporarily swap in the NSApplication object's DPS context to restore access to the application's Window Server state and to the screen. When finished, the view object restores the print operation's context to continue generating its image.
Besides the fundamentals of drawing and event handling, NSView includes several auxiliary features. These are tagging NSViews for quick location, support for dragging of images and file icons, and cooperation with the scrolling machinery to facilitate viewing larger NSViews through smaller ones. The following sections introduce each of these features and name the methods and cooperating classes or protocols involved in each.
NSView defines methods that allow you to tag individual view objects with integer tags and to search the view hierarchy based on those tags. NSView's tag method always returns -1. You can override this in subclasses to return a special value, or even add a setTag: method to allow the tag to be changed at run time (several Application Kit classes, especially NSControl and NSCell, do just this). The viewWithTag method proceeds through all of the receiver's descendants (including itself), searching for a subview with the given tag and returning it if it's found.
A view object can act as either the source or destination for dragged images and file icons. The basic dragging methods, dragImage and dragFile methods, handle the mechanics of moving the image on the screen and notifying the destination of the dragging operations. To act as a source for dragging operations, a concrete subclass of NSView can adopt the NSDraggingSource protocol, by which the source indicates what kinds of dragging operations are allowed and is notified of dragging operations as they begin. Both NSView and NSWindow subclasses can act as destinations for dragging operations, by adopting the NSDraggingDestination protocol and making use of the NSDraggingInfo protocol. For more information see the dragging protocol specifications and the descriptions of dragImage and dragFile in this specification.
NSView defines a number of methods to support scrolling, whereby the NSView being scrolled-the document view-is displayed partially through another-the content or clip view (not to be confused with a window's content view). Scrolling is effected by moving the clip view's bounds rectangle, which reveals the different regions of the document view. Most of the scrolling methods assume that the NSView is enclosed within an NSClipView and an NSScrollView, which handle the mechanics of scrolling for you. You can, however, reproduce the effects of scrolling yourself if you wish. See the NSScrollView, NSClipView, and NSScroller class specifications for information on how scrolling is implemented by the Application Kit.
NSView's most direct scrolling methods are scrollPoint and scrollRectToVisible, both of which assume that the receiver is embedded in an NSClipView. These methods move the clip view so that the requested point or rectangle in the receiver become visible. Another method, autoscroll, automatically scrolls the receiver in an NSClipView based on the location of the mouse. It's useful for moving the document view when the user drags an icon outside of the visible area. The enclosingScrollView method returns the NSScrollView that contains the NSView, allowing you to tune the way scrolling occurs.
Two other methods aid in scrolling. A subclass of NSView can override adjustScroll to change the way automatic (user-driven) scrolling occurs. It can quantize scrolling into regular units, to the edges of a spreadsheet's cells, for example, or simply limit scrolling to a specific region of the NSView. The last scrolling method, scrollRect, copies an already-drawn portion of the NSView to a new location. It's useful for producing temporary effects, but note that any subsequent drawing will obliterate the copied portion.
- Creating instances
- initWithFrame:
- Managing the view hierarchy
- superview
- subviews
- window
- addSubview:
- removeFromSuperview
- removeFromSuperviewWithoutNeedingDisplay
- replaceSubview
- isDescendantOf
- opaqueAncestor
- ancestorSharedWithView
- sortSubviewsUsingFunction:context:
- viewWillMoveToSuperview
- viewWillMoveToWindow
- Searching by tag
- viewWithTag
- tag
- Modifying the frame rectangle
- setFrame
- frame
- setFrameOrigin
- setFrameSize
- setFrameRotation
- frameRotation
- Modifying the bounds rectangle
- setBounds
- bounds
- setBoundsOrigin
- setBoundsSize
- setBoundsRotation
- boundsRotation
- Modifying the coordinate system
- translateOriginToPoint
- scaleUnitSquareToSize
- rotateByAngle
- Examining coordinate system modifications
- isFlipped
- isRotatedFromBase
- isRotatedOrScaledFromBase
- Converting coordinates
- convertPointFromView
- convertPointToView
- convertSizeFromView
- convertSizeToView
- convertRectFromView
- convertRectToView
- centerScanRect
- Controlling notifications
- setPostsFrameChangedNotifications
- postsFrameChangedNotifications
- setPostsBoundsChangedNotifications
- postsBoundsChangedNotifications
- Resizing subviews
- resizeSubviewsWithOldSize
- resizeWithOldSuperviewSize
- setAutoresizesSubviews
- autoresizesSubviews
- setAutoresizingMask
- autoresizingMask
- Focusing
- lockFocus
- unlockFocus
- focusView
- Displaying
- setNeedsDisplay:
- setNeedsDisplayInRect:
- needsDisplay
- display
- displayRect
- displayRectIgnoringOpacity:
- displayIfNeeded
- displayIfNeededInRect
- displayIfNeededIgnoringOpacity
- displayIfNeededInRectIgnoringOpacity
- isOpaque
- Drawing
- drawRect
- visibleRect
- canDraw
- shouldDrawColor
- Setting the interface style
- Managing a graphics state
- allocateGState
- gState
- setUpGState
- renewGState
- releaseGState
- Event handling
- acceptsFirstMouse
- hitTest
- isMouseInRect
- performKeyEquivalent
- performMnemonic
- Dragging operations
- dragImage
- dragFile
- registerForDraggedTypes
- unregisterDraggedTypes
- shouldDelayWindowOrderingForEvent
- Managing cursor rectangles
- addCursorRect
- removeCursorRect
- discardCursorRects
- resetCursorRects
- Managing tool tips
- setToolTip
- toolTip
- Managing tracking rectangles
- addTrackingRect:owner:userData:assumeInside:
- removeTrackingRect
- Scrolling
- scrollPoint
- scrollRectToVisible
- autoscroll
- adjustScroll
- scrollRect
- enclosingScrollView
- scrollClipViewToPoint
- reflectScrolledClipView
- Context-sensitive menus
- menuForEvent
- defaultMenu
- Managing the key view loop
- setNextKeyView
- nextKeyView
- nextValidKeyView
- previousKeyView
- previousValidKeyView
- Printing and faxing
- fax
- dataWithEPSInsideRect
- writeEPSInsideRectToPasteboard
- Pagination
- heightAdjustLimit
- widthAdjustLimit
- knowsPagesFirst:last:
- rectForPage
- locationOfPrintRect
- Adorning pages in printout
- drawPageBorderWithSize
- drawSheetBorderWithSize
- Writing conforming PostScript
- beginPrologue
- endHeaderComments
- endPrologue
- beginSetup
- endSetup
- beginPage
- beginPageSetup
- addToPageSetup
- endPageSetup
- endPage
- beginTrailer
- endTrailer
public NSView(NSRect frameRect)
See Also: - addSubview:, - addSubview:positioned:relativeTo:, - setFrame:
public static NSMenu defaultMenu()
null
. This
menu is used only on Microsoft Windows.See Also: menuForEvent, - menu(NSResponder)
public static NSView focusView()
null
if there is
none.See Also: lockFocus, unlockFocus
public boolean acceptsFirstMouse(NSEvent theEvent)
true
if the receiver should
be sent a mouseDown: message for theEvent,
an initial mouse-down event over the receiver in its window, false
if
not. The receiver can either return a value unconditionally,
or use theEvent's location to determine
whether or not it wants the event. NSView's implementation ignores theEvent and
returns false
.Override this method in a subclass to allow instances to respond to initial mouse-down events. For example, most view objects refuse an initial mouse-down event, so the event simply activates the window. Many control objects, however, such as NSButton and NSSlider, do accept them, so the user can immediately manipulate the control without having to release the mouse button.
See Also: hitTest
public void addCursorRect(NSRect aRect, NSCursor aCursor)
This method is intended to be invoked only by the resetCursorRects method. If invoked in any other way, the resulting cursor rectangle will be discarded the next time the NSView's cursor rectangles are rebuilt.
See Also: removeCursorRect, discardCursorRects, resetCursorRects, visibleRect
public void addSubview(NSView aView, int place, NSView otherView)
WindowAbove
or WindowBelow
. If otherView is null (or
isn't a subview of the receiver), aView is
added above or below all of its new siblings. Also sets the receiver
as aView's next responder.
public void addSubview(NSView aView)
See Also: - subviews, - removeFromSuperview, - setNextResponder: (NSResponder), - viewWillMoveToSuperview:, - viewWillMoveToWindow:
public void addToPageSetup()
See the NSPrintInfo class specification for information on retrieving document scaling during printing.
See Also: beginPageSetup
public NSRect adjustScroll(NSRect proposedVisibleRect)
NSClipView only invokes this method during automatic or user-controlled scrolling. Its scrollToPoint: method doesn't invoke this method, so you can still force a scroll to an arbitrary point.
public void allocateGState()
The receiver builds the graphics state parameters using setUpGState, then automatically establishes this graphics state each time the PostScript focus is locked on it. A graphics state may improve performance for view objects that are focused often and need to set many parameters, but use of standard PostScript operators is normally efficient enough.
Because graphics states occupy a fair amount of memory, they can actually degrade performance. Be sure to test application performance with and without the private graphics state before committing to its use.
See Also: setUpGState, gState, renewGState, releaseGState, lockFocus
public NSView ancestorSharedWithView(NSView aView)
null
if there's no such object. Returns this if aView is
identical to the receiver.See Also: isDescendantOf
public boolean autoresizesSubviews()
true
if
the receiver automatically resizes its subviews using resizeSubviewsWithOldSize whenever
its frame size changes, false
otherwise.See Also: setAutoresizesSubviews
public int autoresizingMask()
ViewNotSizable
(that
is, if none of the options are set), then the receiver doesn't
resize at all in resizeWithOldSuperviewSize.public boolean autoscroll(NSEvent theEvent)
true
if
any scrolling is performed; otherwise returns false
.View objects that track mouse-dragged events can use this method to scroll automatically when the mouse is dragged outside of the NSClipView. Repeated invocations of this method (with an appropriate delay) result in continual scrolling, even when the mouse doesn't move.
See Also: - autoscroll: (NSClipView), scrollPoint, isDescendantOf
public void beginPage(int ordinalNum, String aString, NSRect pageRect, String fontNames)
ordinalNum is the page's position in the document's page sequence (from 1 through n for an n-page document).
aString is a string that contains no white space characters. It identifies the page according to the document's internal numbering scheme. If aString is empty (""), the text equivalent of ordinalNum is used.
pageRect is the rectangle enclosing all the drawing on the page about to be printed, in the default PostScript coordinate system of the page (not of the receiving NSView). If pageRect is an empty rectangle (width and height of zero), "(atend)" is output instead of a description of the bounding box, and the bounding box is output at the end of the page.
fontNames is a string containing the names of the fonts used in the page, each pair separated by a space. If the fonts used are unknown before the page is printed, fontNames can be empty. In this case "(atend)" is output instead of the font names, which are listed automatically at the end of the page description.
See Also: endPage, NSIsEmptyRect() (Foundation Kit)
public void beginPageSetup(NSRect aRect, NSPoint location)
This method is invoked by print and fax after the starting comments for
the page have been written. It generates a PostScript save
operation
and invokes lockFocus,
which are balanced in the endPage method
with an unlockFocus and
a PostScript restore
operation.
See Also: addToPageSetup
public void beginPrologue(NSRect boundingBox, String dateCreated, String anApplication, String fontNames, String user, int numPages, String aTitle)
boundingBox is the bounding box of the document, expressed in the default PostScript coordinate system on the page. The document bounding box is the union of the bounding boxes of every page in the document. If it's unknown, boundingBox should be empty (width and height of zero). In this case "(atend)" is output instead of the bounding box, which is accumulated as pages are printed and written in the trailer.
dateCreated is a text string containing a human readable date. If dateCreated is empty ("") the current date is used.
anApplication is a string containing the name of the document creator. If anApplication is empty then the string returned by NSProcessInfo's processName instance method is used.
fontNames is a string holding the names of the fonts used in the document, each pair separated by a space. If the fonts used are unknown before the document is printed, fontNames should be empty. In this case "(atend)" is output instead of the font names, and the name of each NSFont used by the view is written in the trailer.
user is a string containing the name of the person the document is being printed for. If user is empty the login name of the current user is substituted.
numPages specifies the number of pages in the document. If unknown at the beginning of printing, numPages should have a value of -1. In this case "(atend)" is output instead of a page count, the pages are counted as they are generated, and the resulting count is written in the trailer.
aTitle is a string specifying the title of the document. If aTitle is empty, then the title of the receiver's window is used. If the window has no title, "Untitled" is output.
See Also: beginTrailer, endTrailer, - set (NSFont) + useFont: (NSFont)
public void beginSetup()
%%BeginSetup
comment
and includes a %%PaperSize
comment
declaring the type of paper being used. This method
is invoked by print and fax at the start of
the setup section of the document, which occurs after the prologue
of the document has been written, but before any pages are written.
This section of the output is intended for device setup or general
initialization code.public void beginTrailer()
%%Trailer
comment. This
method is invoked by print and fax immediately after
all pages have been written.public NSRect bounds()
public float boundsRotation()
See Also: rotateByAngle, setBoundsRotation
public boolean canDraw()
true
if
drawing commands will produce any result, false
otherwise. Use
this method when invoking a draw method directly along with lockFocus and unlockFocus, bypassing
the display... methods (which test drawing ability
and perform locking for you). If this method returns false
,
you shouldn't invoke lockFocus or
perform any drawing.An NSView can draw if it's attached to a view hierarchy in an NSWindow and the NSWindow has a corresponding PostScript window device, or during printing if the NSView is a descendant of the view being printed.
public NSRect centerScanRect(NSRect aRect)
See Also: isRotatedOrScaledFromBase
public NSPoint convertPointFromView(NSPoint aPoint, NSView aView)
null
,
this method instead converts from window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
point.See Also: convertRectFromView, convertSizeFromView, ancestorSharedWithView, - contentView (NSWindow)
public NSPoint convertPointToView(NSPoint aPoint, NSView aView)
null
,
this method instead converts to window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
point.See Also: convertRectToView, convertSizeToView, ancestorSharedWithView, - contentView (NSWindow)
public NSRect convertRectFromView(NSRect aRect, NSView aView)
null
,
this method instead converts from window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
rectangle.See Also: convertPointFromView, convertSizeFromView, ancestorSharedWithView, - contentView (NSWindow)
public NSRect convertRectToView(NSRect aRect, NSView aView)
null
,
this method instead converts to window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
rectangle.See Also: convertPointToView, convertSizeToView, ancestorSharedWithView, - contentView (NSWindow)
public NSSize convertSizeFromView(NSSize aSize, NSView aView)
null
,
this method instead converts from window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
size.See Also: convertPointFromView, convertRectFromView, ancestorSharedWithView, - contentView (NSWindow)
public NSSize convertSizeToView(NSSize aSize, NSView aView)
null
,
this method instead converts to window base coordinates. Both aView and
the receiver must belong to the same NSWindow. Returns the converted
size.See Also: convertPointToView, convertRectToView, ancestorSharedWithView, - contentView (NSWindow)
public NSData dataWithEPSInsideRect(NSRect aRect)
See Also: writeEPSInsideRectToPasteboard
public void discardCursorRects()
See Also: - discardCursorRects (NSWindow)
public void display()
See Also: canDraw, opaqueAncestor, visibleRect, displayIfNeededIgnoringOpacity
public void displayIfNeeded()
See Also: display, needsDisplay, displayIfNeededIgnoringOpacity
public void displayIfNeededIgnoringOpacity()
public void displayIfNeededInRect(NSRect aRect)
public void displayIfNeededInRectIgnoringOpacity(NSRect aRect)
public void displayRect(NSRect aRect)
public void displayRectIgnoringOpacity(NSRect aRect)
public boolean dragFile(String fullPath, NSRect aRect, boolean slideBack, NSEvent theEvent)
true
if the receiver successfully
initiates the dragging operation (which doesn't necessarily mean
the dragging operation concluded successfully). Otherwise returns false
.The dragging operation uses these arguments:
true
,
the file is not accepted by the dragging destination, and the user
has not disabled icon animation; otherwise it simply disappears.See the NSDraggingSource, NSDraggingInfo, and NSDraggingDestination protocol specifications for more information on dragging operations.
See Also: dragImage, shouldDelayWindowOrderingForEvent
public void dragImage(NSImage anImage, NSPoint imageLoc, NSSize mouseOffset, NSEvent theEvent, NSPasteboard pboard, Object sourceObject, boolean slideBack)
true
,
the image isn't accepted by the dragging destination, and the
user hasn't disabled icon animation; otherwise it simply disappears.Before
invoking this method, you must place the data to be transferred
on pboard. To do this, get the drag
pasteboard object (NSPasteboard.DragPboard
), declare
the types of the data, and then put the data on the pasteboard.
See the NSDraggingSource, NSDraggingInfo, and NSDraggingDestination protocol specifications for more information on dragging operations.
See Also: dragFile, shouldDelayWindowOrderingForEvent
public void drawPageBorderWithSize(NSSize borderSize)
See Also: drawSheetBorderWithSize
public void drawRect(NSRect aRect)
This method is intended to be completely overridden
by each subclass that performs drawing. Don't invoke super
's
implementation in your subclass.
See Also: display, shouldDrawColor, isFlipped
public void drawSheetBorderWithSize(NSSize borderSize)
See Also: drawPageBorderWithSize
public NSScrollView enclosingScrollView()
null
.public void endHeaderComments()
%%EndComments
line
and then the start of the prologue, including the Application Kit's
standard printing package. Override endPrologue to add
your own global definitions. This method is invoked by print and fax after beginPrologue and
before endPrologue.public void endPage()
restore
operator,
and generates a PostScript showpage
operator
to finish the page. This method also generates comments for the
bounding box and page fonts, if they were specified as being at
the end of the page.See Also: beginPrologue
public void endPageSetup()
%%EndPageSetup
comment. This
method is invoked by print and fax just after beginPageSetup is
invoked.public void endPrologue()
public void endSetup()
%%EndSetup
comment. This
method is invoked by print and fax just after beginSetup is invoked.public void endTrailer()
See Also: beginTrailer
public void fax(Object sender)
See Also: print
public NSRect frame()
public float frameRotation()
See Also: setFrameRotation, boundsRotation
public int gState()
Although applications rarely need to use the value returned by gState , it can be passed to the few PostScript operators that take an object identifier as a parameter, such as PScomposite and PSdissolve.
See Also: allocateGState, setUpGState, renewGState, releaseGState, lockFocus
public float heightAdjustLimit()
See Also: widthAdjustLimit
public NSView hitTest(NSPoint aPoint)
null
if aPoint lies
completely outside the receiver. aPoint is
in the coordinate system of the receiver's superview, not of the
receiver itself.This method is used primarily by an NSWindow to determine which NSView should receive a mouse-down event. You'd rarely need invoke this method, but you might want to override it to have a view object hide mouse-down events from its subviews.
See Also: isMouseInRect, convertPointToView
public boolean isDescendantOf(NSView aView)
See Also: superview, subviews, ancestorSharedWithView
public boolean isFlipped()
true
if
the receiver uses flipped drawing coordinates or false
if
it uses native PostScript coordinates. NSView's
implementation returns false
; subclasses
that use flipped coordinates should override this method to return true
.public boolean isOpaque()
true
if the receiver is opaque, false
otherwise. A
view object is opaque if it completely covers its frame rectangle when
drawing itself. NSView, being an abstract class, performs no drawing
at all and so returns false
.See Also: opaqueAncestor, displayRectIgnoringOpacity:, displayIfNeededIgnoringOpacity, displayIfNeededInRectIgnoringOpacity
public boolean isRotatedFromBase()
true
if
the receiver or any of its ancestors has ever received a setFrameRotation or setBoundsRotation message;
otherwise returns false
. This
intent of this information is to optimize drawing and coordinate calculation,
not necessarily to reflect the exact state of the receiver's coordinate system,
so it may not reflect the actual rotation. For example, if an NSView
is rotated to 45 degrees and later back to zero, this method still
returns true
.See Also: frameRotation, boundsRotation
public boolean isRotatedOrScaledFromBase()
true
if
the receiver or any of its ancestors have ever had a nonzero frame
or bounds rotation, or has been scaled from the window's base
coordinate system; otherwise returns false
. This
intent of this information is to optimize drawing and coordinate
calculation, not necessarily to reflect the exact state of the receiver's
coordinate system, so it may not reflect the actual rotation or
scaling. For example, if an NSView is rotated to 45 degrees and
later back to zero, this method still returns true
.See Also: frameRotation, boundsRotation, centerScanRect, setBounds, setBoundsSize, scaleUnitSquareToSize
public boolean knowsPageRange(NSMutableRange aRange)
public NSPoint locationOfPrintRect(NSRect aRect)
NSView's
implementation places aRect according
to the status of the NSPrintInfo object for the print job. By default
it places the image in the upper left corner of the page, but if
NSPrintInfo's isHorizontallyCentered or isVerticallyCentered method
returns true
, it centers a single-page
image along the appropriate axis. A multiple-page document, however,
is always placed so the divided pieces can be assembled at their
edges.
public void lockFocus()
See Also: focusView, display, drawRect
public NSMenu menuForEvent(NSEvent theEvent)
NSView's implementation returns the receiver's normal menu. This menu is used only on Microsoft Windows.
See Also: defaultMenu, - menu (NSResponder)
public boolean isMouseInRect(NSPoint aPoint, NSRect aRect)
true
if aRect contains aPoint (which
represents the hot spot of the mouse cursor), accounting for whether
the receiver is flipped or not. aPoint and aRect must
be expressed in the receiver's coordinate system.See Also: hitTest, isFlipped, NSMouseInRect() (Foundation Kit), convertPointFromView
public boolean needsDisplay()
true
if
the receiver needs to be displayed, as indicated using the setNeedsDisplay: and setNeedsDisplayInRect: methods;
returns false
otherwise. The displayIfNeeded... methods
check this status to avoid unnecessary drawing, and all display
methods clear this status to indicate that the view object is up
to date.public boolean needsPanelToBecomeKey()
true
if the receiver requires
its panel, which might otherwise avoid becoming key, to become the
key window so that it can handle keyboard input. Such
a subclass should also override acceptsFirstResponder to
return true
. NSView's implementation
returns false
.See Also: - becomesKeyOnlyIfNeeded (NSPanel)
public NSView nextKeyView()
null
if there
is none. This view should, if possible, be made
first responder when the user navigates forward from the receiver
using keyboard interface control.See Also: nextValidKeyView, setNextKeyView, previousKeyView, previousValidKeyView
public NSView nextValidKeyView()
null
if
there is none.See Also: nextKeyView, setNextKeyView, previousKeyView, previousValidKeyView
public NSView opaqueAncestor()
See Also: isOpaque, displayRectIgnoringOpacity:, displayIfNeededIgnoringOpacity, displayIfNeededInRectIgnoringOpacity
public boolean performKeyEquivalent(NSEvent theEvent)
true
.
Otherwise, it should return the result of invoking super
's
implementation. NSView's implementation of this method simply
passes the message down the view hierarchy (from superviews to subviews)
and returns false
if none of the
receiver's subviews responds true
.See Also: performMnemonic, - keyDown: (NSWindow)
public boolean performMnemonic(String aString)
true
.
Otherwise, it should return the result of invoking super
's
implementation. NSView's implementation of this method simply
passes the message down the view hierarchy (from superviews to subviews)
and returns false
if none of the
receiver's subviews responds true
.See Also: performKeyEquivalent, - keyDown: (NSWindow)
public boolean postsBoundsChangedNotifications()
true
if
the receiver posts notifications to the default notification center whenever
its bounds rectangle changes; returns false
otherwise. See setPostsBoundsChangedNotifications for
a list of methods that result in notifications.public boolean postsFrameChangedNotifications()
true
if
the receiver posts notifications to the default notification center whenever
its frame rectangle changes; returns false
otherwise. See setFrameRotation for
a list of methods that result in notifications.public NSView previousKeyView()
null
if there
is none. This view should, if possible, be made
first responder when the user navigates backward from the receiver
using keyboard interface control.See Also: previousValidKeyView, nextKeyView, nextValidKeyView, setNextKeyView
public NSView previousValidKeyView()
null
if
there is none.See Also: previousKeyView, nextValidKeyView, nextKeyView, setNextKeyView
public void print(Object sender)
See Also: fax, dataWithEPSInsideRect, writeEPSInsideRectToPasteboard
public NSRect rectForPage(int pageNumber)
true
to
an earlier knowsPagesFirst:last: message,
this method is invoked for each page it specified in the out parameters
of that message. The receiver is later made to display this rectangle
in order to generate the image for this page. This method should
return NSZeroRect if pageNumber is
outside the receiver's bounds.If an NSView responds false to knowsPagesFirst:last:, this method isn't invoked by the printing mechanism.
See Also:
public void reflectScrolledClipView(NSClipView aClipView)
public void registerForDraggedTypes(NSArray pboardTypes)
Registering an NSView for dragged types automatically makes it a candidate destination object for a dragging session. As such, it must properly implement some or all of the NSDraggingDestination protocol methods. As a convenience, NSView provides default implementations of these methods. See the NSDraggingDestination protocol specification for details.
See Also: unregisterDraggedTypes
public void releaseGState()
See Also: allocateGState
public void removeCursorRect(NSRect aRect, NSCursor aCursor)
You should rarely need to use this method. resetCursorRects, which is invoked any time cursor rectangles need to be rebuilt, should establish only the cursor rectangles needed. If you implement resetCursorRects in this way, you can then simply modify the state that resetCursorRects uses to build its cursor rectangles and then invoke NSWindow's invalidateCursorRectsForView:.
See Also: discardCursorRects
public void removeFromSuperview()
Never invoke this method during display.
See Also: addSubview:removeFromSuperviewWithoutNeedingDisplay
public void removeFromSuperviewWithoutNeedingDisplay()
Unlike its counterpart, removeFromSuperview, this method can be safely invoked during display.
See Also: addSubview:
public void removeTrackingRect(int aTag)
public void renewGState()
See Also: lockFocus
public void replaceSubview(NSView oldView, NSView newView)
null
if oldView is
not a subview of the receiver.See Also: addSubview:
public void resetCursorRects()
Application code should never invoke this method directly; it's invoked automatically as described in the Tracking Rectangles and Cursor Rectangles section. Use the invalidateCursorRectsForView: method instead to explicitly rebuild cursor rectangles.
See Also: visibleRect
public void resizeSubviewsWithOldSize(NSSize oldFrameSize)
NSView's implementation sends resizeWithOldSuperviewSize to the receiver's subviews with oldFrameSize as the argument. You shouldn't invoke this method directly, but you can override it to define a specific retiling behavior.
See Also: setAutoresizesSubviews
public void resizeWithOldSuperviewSize(NSSize oldFrameSize)
NSView's implementation resizes the receiver according to the autoresizing options listed under the setAutoresizingMask method description. You shouldn't invoke this method directly, but you can override it to define a specific resizing behavior.
public void rotateByAngle(float angle)
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: setFrameRotation, setPostsBoundsChangedNotifications
public void scaleUnitSquareToSize(NSSize newUnitSize)
This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: setBoundsSize, setPostsBoundsChangedNotifications
public void scrollClipViewToPoint(NSClipView aClipView, NSPoint newOrigin)
See Also: - scrollToPoint: (NSClipView)
public void scrollPoint(NSPoint aPoint)
See Also: autoscroll, - scrollToPoint: (NSClipView), isDescendantOf
public void scrollRect(NSRect aRect, NSSize offset)
You should rarely need to use this method, however. The scrollPoint, scrollRectToVisible, and autoscroll methods automatically perform optimized scrolling.
See Also: setBoundsOrigin, translateOriginToPoint
public boolean scrollRectToVisible(NSRect aRect)
true
if
any scrolling is performed; otherwise returns false
.See Also: autoscroll, - scrollToPoint: (NSClipView), isDescendantOf
public void setAutoresizesSubviews(boolean flag)
true
,
the receiver invokes resizeSubviewsWithOldSize whenever
its frame size changes; if flag is false
,
it doesn't. View objects do autoresize their subviews by default.See Also: autoresizesSubviews
public void setAutoresizingMask(int mask)
Option | Meaning |
ViewMinXMargin |
The left margin between the receiver and its superview is flexible. |
ViewWidthSizable |
The receiver's width is flexible. |
ViewMaxXMargin |
The right margin between the receiver and its superview is flexible. |
ViewMinYMargin |
The bottom margin between the receiver and its superview is flexible. |
ViewHeightSizable |
The receiver's height is flexible. |
ViewMaxYMargin |
The top margin between the receiver and its superview is flexible. |
Where more than one option along an axis is set, resizeWithOldSuperviewSize by
default distributes the size difference as evenly as possible among
the flexible portions. For example, if ViewWidthSizable
and ViewMaxXMargin
are
set and the superview's width has
increased by 10.0 units, the receiver's frame and right margin
are each widened by 5.0 units.
See Also: autoresizingMask, resizeSubviewsWithOldSize, setAutoresizesSubviews
public void setBounds(NSRect boundsRect)
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: bounds, setBoundsRotation, setBoundsOrigin, setBoundsSize, setFrame, setPostsBoundsChangedNotifications
public void setBoundsOrigin(NSPoint newOrigin)
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: translateOriginToPoint, bounds, setBoundsRotation, setBounds, setBoundsSize, setPostsBoundsChangedNotifications
public void setBoundsRotation(float angle)
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
Bounds rotation affects the orientation of the drawing within the view object's frame rectangle, but not the orientation of the frame rectangle itself. Also, for a rotated bounds rectangle to enclose all the visible areas of its view object-that is, to guarantee coverage over the frame rectangle-it must also contain some areas that aren't visible. This can cause unnecessary drawing to be requested, which may affect performance. It may be better in many cases to rotate the PostScript coordinate system in the drawRect method rather than use this method.
See Also: rotateByAngle, boundsRotation, setFrameRotation, setPostsBoundsChangedNotifications
public void setBoundsSize(NSSize newSize)
This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: bounds, setBoundsRotation, setBounds, setBoundsOrigin, setPostsBoundsChangedNotifications
public void setFrame(NSRect frameRect)
This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: frame, setFrameRotation, setFrameOrigin, setFrameSize, setBounds, setPostsFrameChangedNotifications
public void setFrameOrigin(NSPoint newOrigin)
This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: frame, setFrameSize, setFrame, setFrameRotation, setPostsFrameChangedNotifications
public void setFrameRotation(float angle)
This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay:.
This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: frameRotation, setBoundsRotation
public void setFrameSize(NSSize newSize)
This method posts an NSViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: frame, setFrameOrigin, setFrame, setFrameRotation, setPostsFrameChangedNotifications
public void setNeedsDisplay(boolean aFlag)
true
,
marks the receiver's entire bounds as needing display; if flag is false
,
marks it as not needing display. Whenever the
data or state used for drawing a view object changes, the view should
be sent this message. NSViews marked as needing display are automatically
redisplayed on each pass through the application's event loop.
(View objects that need to redisplay before the event loop comes
around can of course immediately be sent the appropriate display... method.)
public void setNeedsDisplay(NSRect invalidRect)
See Also: - needsDisplay
public void setNextKeyView(NSView aView)
See Also: nextKeyView, nextValidKeyView, previousKeyView, previousValidKeyView
- (void)setPostsBoundsChangedNotifications:(BOOL)flag
true
,
the receiver will post notifications to the default notification
center whenever its bounds rectangle changes; if flag is false
it won't.
The following methods can result in notification posting:
See Also: postsBoundsChangedNotifications
public void setPostsFrameChangedNotifications(boolean flag)
true
,
the receiver will post notifications to the default notification
center whenever its frame rectangle changes; if flag is false
it won't.
The following methods can result in notification posting:
See Also: postsFrameChangedNotifications
public void setToolTip(String string)
null
,
cancels tooltip display for the view.See Also: toolTip
public void setUpGState()
See Also: allocateGState, renewGState
public boolean shouldDelayWindowOrderingForEvent(NSEvent theEvent)
- (BOOL)shouldDelayWindowOrderingForEvent:(NSEvent
*)theEvent
true
,
the normal window ordering and activation mechanism is delayed (not
necessarily prevented) until the next mouse-up event. If it returns false
then
normal ordering and activation occurs. Never invoke this method
directly; it's invoked automatically for each mouse-down event
directed at the NSView.An NSView subclass that allows dragging
should implement this method to return true
if theEvent,
an initial mouse-down event, is potentially the beginning of a dragging
session or of some other context where window ordering isn't appropriate.
This method is invoked before a mouseDown: message
for theEvent is sent. NSView's
implementation returns false
.
If,
after delaying window ordering, the receiver actually initiates
a dragging session or similar operation, it should also send a preventWindowOrdering message
to NSApp
, which completely prevents
the window from ordering forward and the activation from becoming
active. preventWindowOrdering is sent automatically
by NSView's dragImage:... and dragFile:... methods.
public boolean shouldDrawColor()
false
if
the receiver is being drawn in an NSWindow (as opposed, for example,
to being printed) and the NSWindow can't store color; otherwise
returns true
. An
NSView can base its drawing behavior on the return value of this method
to improve its appearance in grayscale windows.See Also: drawRect, - canStoreColor (NSWindow)
public NSArray subviews()
See Also: addSubview:superview, removeFromSuperview
public NSView superview()
null
if it has none. When
applying this method iteratively or recursively, be sure to compare
the returned NSView to the content view of the NSWindow to avoid
proceeding out of the view hierarchy.See Also: window, subviews, removeFromSuperview
public int tag()
See Also: viewWithTag
public String toolTip()
null
if
the view doesn't currently display tooltip text.See Also: setToolTip
public void translateOriginToPoint(NSPoint newOrigin)
-
newOrigin.x
, -
newOrigin.y
).
This method neither redisplays the receiver nor marks it as needing
display. You must do this yourself with display or setNeedsDisplay:.Note the difference between this method and setting the bounds origin. Translation effectively moves the image inside the bounds rectangle, while setting the bounds origin effectively moves the rectangle over the image. The two are in a sense inverse, although translation is cumulative and setting the bounds origin is absolute.
This method posts an NSViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.
See Also: setBoundsOrigin, setBounds, setPostsBoundsChangedNotifications
public void unlockFocus()
See Also: allocateGState
public void unregisterDraggedTypes()
See Also: - registerForDraggedTypes:
public void viewWillMoveToSuperview(NSView newSuperview)
See Also: viewWillMoveToWindow
public void viewWillMoveToWindow(NSWindow newWindow)
See Also: viewWillMoveToSuperview
public NSView viewWithTag(int aTag)
null
if
no subview has that tag.See Also: tag
public NSRect visibleRect()
During a printing operation the visible rectangle is further clipped to the page being imaged.
See Also: - isVisible (NSWindow), - documentVisibleRect (NSScrollView) - documentVisibleRect (NSClipView)
public float widthAdjustLimit()
See Also: heightAdjustLimit
public NSWindow window()
null
if it has none.See Also: superview
public void writeEPSInsideRectToPasteboard(NSRect aRect, NSPasteboard pboard)
See Also: dataWithEPSInsideRect
Posted whenever the NSView's bounds rectangle changes independently of the frame rectangle, if the NSView is configured using setPostsBoundsChangedNotifications: to post such notifications.
This notification contains a notification object but no userInfo dictionary. The notification object is the NSView whose bounds rectangle has changed.
The following methods can result in notification posting:
Note that the bounds rectangle resizes automatically to track the frame rectangle. Because the primary change is that of the frame rectangle, however, setFrame: and setFrameSize: don't result in a bounds-changed notification.
Posted whenever the NSView loses the PostScript focus other than by an unlockFocus message (for example, when its frame or bounds rectangle is changed).
This notification contains a notification object but no userInfo dictionary. The notification object is the NSView that has lost focus.
See Also: focusView
Posted whenever the NSView's frame rectangle changes, if the NSView is configured using setPostsFrameChangedNotifications: to post such notifications.
This notification contains a notification object but no userInfo dictionary. The notification object is the NSView whose frame rectangle has changed.
The following methods can result in notification posting: