Next Page > Hide TOC

Legacy Documentclose button

Important: The information in this document is obsolete and should not be used for new development.

NSView

Inherits from
Implements
Package
com.apple.cocoa.application
Companion guides

Class at a Glance

NSView is an abstract class that defines the basic drawing, event-handling, and printing architecture of an application. You typically don’t interact with the NSView API directly; rather, your custom view classes inherit from NSView and override many of its methods, which are invoked automatically by the Application Kit. If you’re not creating a custom view class, there are few methods you need to use.

Principal Attributes

Commonly Used Methods

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.)

Overview

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.

Most of the functionality of NSView either is 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 runtime, you don’t need to know much about this class’s interface. See “Commonly Used Methods” for methods you might use regardless.

For more information on how NSViews handle event and action messages, see “Handling Events in Views”, “Handling Mouse Events in Views”, and “Handling Tracking-Rectangle and Cursor-Update Events in Views”. For more information on displaying tooltips and contextual menus, see “How Contextual Menus Work” and “Tooltips”.

Subclassing Notes

NSView is perhaps the most important class in the Application Kit when it comes to subclassing and inheritance. Most user-interface objects you see in a Cocoa application are objects that inherit from NSView. If you want to create an object that draws itself in a special way, or that responds to mouse clicks in a special way, you would create a custom subclass of NSView (or of a class that inherits from NSView). Subclassing NSView is such a common and important procedure that several technical documents describe how to both draw in custom subclasses and respond to events in custom subclasses. See Drawing and Views Programming Topics for Cocoa (especially “Drawing in a View”) and Cocoa Event-Handling Guide (especially “Handing Events in View” and “Handling Mouse Events in Views”).

Tasks

Constructors

Managing the View Hierarchy

Searching by Tag

Modifying the Frame Rectangle

Modifying the Bounds Rectangle

Modifying the Coordinate System

Examining Coordinate System Modifications

Converting Coordinates

Controlling Notifications

Resizing Subviews

Focusing

Displaying

Hiding Views

Drawing

Managing Live Resize

Managing a Graphics State

Event Handling

Dragging Operations

Managing Cursor Rectangles

Managing Tool Tips

Managing Tracking Rectangles

Scrolling

Context-sensitive Menus

Managing the Key View Loop

Printing

Pagination

Adorning Pages in Printout

Writing Conforming Rendering Instructions

Constructors

NSView

Creates an NSView with a zero-sized frame rectangle.

public NSView()

Creates an NSView with frameRect as its frame rectangle.

public NSView(NSRect frameRect)

Discussion

The new view object must be inserted into the view hierarchy of an NSWindow before it can be used.

See Also

Static Methods

defaultFocusRingType

public static int defaultFocusRingType()

Discussion

Returns the default type of focus ring for objects of the receiver’s class. If NSGraphics.FocusRingTypeDefault is returned from the instance method focusRingType, the receiver can invoke this class method to find out what type of focus ring is the default. The receiver is free to ignore the default setting.Possible return values are listed in the “Constants” section of NSGraphics.

Availability

defaultMenu

Overridden by subclasses to return the default pop-up menu for instances of the receiving class.

public static NSMenu defaultMenu()

Discussion

NSView’s implementation returns null.

See Also

focusView

Returns the currently focused NSView object, or null if there is none.

public static NSView focusView()

See Also

Instance Methods

acceptsFirstMouse

Overridden by subclasses to return 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.

public boolean acceptsFirstMouse(NSEvent theEvent)

Discussion

The receiver can either return a value unconditionally, or use the location of theEvent 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 click-through. This allows the user to click on a view in an inactive window, activating the view with one click, instead of clicking first to make the window active and then clicking the view. Most view objects refuse a click-through attempt, 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

addCursorRect

Establishes aCursor as the cursor to be used when the mouse pointer lies within aRect.

public void addCursorRect(NSRect aRect, NSCursor aCursor)

Discussion

Cursor rectangles aren’t subject to clipping by superviews, nor are they intended for use with rotated NSViews. You should explicitly confine a cursor rectangle to the NSView’s visible rectangle to prevent improper behavior.

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

addSubview

Inserts aView among the receiver’s subviews so it’s displayed immediately above or below otherView according to whether place is NSWindow.Above or NSWindow.Below.

public void addSubview(NSView aView, int place, NSView otherView)

Discussion

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 the next responder to aView.

Adds aView to the receiver’s subviews so it’s displayed above its siblings.

public void addSubview(NSView aView)

Discussion

Also sets the receiver as the next responder to aView.

See Also

addTrackingRect

Establishes aRect as an area for tracking mouse-entered and mouse-exited events within the receiver and returns a tag that identifies the tracking rectangle in NSEvent objects and can be used to remove the tracking rectangle.

public int addTrackingRect(NSRect aRect, Object userObject, Object userData, boolean flag)

Discussion

userObject is the object that gets sent the event messages. It can be the receiver itself or some other object (such as an NSCursor or a custom drawing tool object), as long as it responds to both mouseEntered and mouseExited. Your application is responsible for making sure that userObject is referenced elsewhere so it doesn't get garbage-collected. userData is supplied in the NSEvent object for each tracking event. flag determines which event is sent first by indicating where the cursor is assumed to be at the time this method is invoked. If flag is true, the first event will be generated when the cursor leaves aRect; if flag is false the first event will be generated when the cursor enters it.

Tracking rectangles provide a general mechanism that can be used to trigger actions based on the cursor location (for example, a status bar or hint field that provides information on the item the cursor lies over). To simply change the cursor over a particular area, use addCursorRect. If you must use tracking rectangles to change the cursor, the NSCursor class specification describes the additional methods that must be invoked to change cursors by using tracking rectangles.

Availability
See Also

adjustPageHeight

Overridden by subclasses to adjust page height during automatic pagination.

public float adjustPageHeight(float top, float proposedBottom, float bottomLimit)

Discussion

This method is invoked by print with top and proposedBottom set to the top and bottom edges of the pending page rectangle in the receiver’s coordinate system. The receiver can raise the bottom edge and return the new value, allowing it to prevent items such as lines of text from being divided across pages. bottomLimit is the topmost value the return value can be set to, as calculated using the return value of heightAdjustLimit. If this limit is exceeded, the pagination mechanism simply uses bottomLimit for the bottom edge.

NSView’s implementation of this method propagates the message to its subviews, allowing nested views to adjust page height for their drawing as well. An NSButton or other small view, for example, will nudge the bottom edge up if necessary to prevent itself from being cut in two (thereby pushing it onto an adjacent page). Subclasses should invoke super’s implementation, if desired, after first making their own adjustments.

Availability
See Also

adjustPageWidth

Overridden by subclasses to adjust page width during automatic pagination.

public native float adjustPageWidth(float left, float proposedRight, float rightLimit)

Discussion

This method is invoked by print, with left and proposedRight set to the side edges of the pending page rectangle in the receiver’s coordinate system. The receiver can pull in the right edge and return the new value, allowing it to prevent items such as small images or text columns from being divided across pages. rightLimit is the leftmost value the return value can be set to, as calculated using the return value of widthAdjustLimit. If this limit is exceeded, the pagination mechanism simply uses rightLimit for the right edge.

NSView’s implementation of this method propagates the message to its subviews, allowing nested views to adjust page width for their drawing as well. An NSButton or other small view, for example, will nudge the right edge out if necessary to prevent itself from being cut in two (thereby pushing it onto an adjacent page). Subclasses should invoke super’s implementation, if desired, after first making their own adjustments.

Availability
See Also

adjustScroll

Overridden by subclasses to modify proposedVisibleRect, returning the altered rectangle.

public NSRect adjustScroll(NSRect proposedVisibleRect)

Discussion

NSClipView invokes this method to allow its document view to adjust its position during scrolling. For example, a custom view object that displays a table of data can adjust the origin of proposedVisibleRect so rows or columns aren’t cut off by the edge of the enclosing NSClipView. NSView’s implementation simply returns 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.

allocateGState

Causes the receiver to maintain a private graphics state object, which encapsulates all parameters of the graphics environment.

public void allocateGState()

Discussion

If you do not invoke allocateGState, a graphics state object is constructed from scratch each time the NSView is focused.

The receiver builds the graphics state parameters using setUpGState, then automatically establishes this graphics state each time the 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 rendering 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

ancestorSharedWithView

Returns the closest ancestor shared by the receiver and aView, or null if there’s no such object.

public NSView ancestorSharedWithView(NSView aView)

Discussion

Returns this if aView is identical to the receiver.

See Also

autoresizesSubviews

Returns true if the receiver automatically resizes its subviews using resizeSubviewsWithOldSize whenever its frame size changes, false otherwise.

public boolean autoresizesSubviews()

See Also

autoresizingMask

Returns the receiver’s autoresizing mask, which determines how it’s resized by the resizeWithOldSuperviewSize method.

public int autoresizingMask()

Discussion

The autoresizing mask values are listed under the setAutoresizingMask method description. If the autoresizing mask is equal to ViewNotSizable (that is, if none of the options are set), then the receiver doesn’t resize at all in resizeWithOldSuperviewSize.

autoscroll

Scrolls the receiver’s closest ancestor NSClipView proportionally to the distance of theEvent outside of it.

public boolean autoscroll(NSEvent theEvent)

Discussion

The location of theEvent should be expressed in the window’s base coordinate system (which it normally is), not the receiving view object’s. Returns 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 cursor 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

bounds

Returns the receiver’s bounds rectangle, which expresses its location and size in its own coordinate system.

public NSRect bounds()

Discussion

The bounds rectangle may be rotated; use the boundsRotation method to check this.

See Also

boundsRotation

Returns the angle, in degrees, of the receiver’s bounds rectangle relative to its frame rectangle.

public float boundsRotation()

Discussion

See the setBoundsRotation method description for more information on bounds rotation.

See Also

canBecomeKeyView

Returns whether the receiver can become key view.

public boolean canBecomeKeyView()

Availability

canDraw

Returns true if drawing commands will produce any result, false otherwise.

public boolean canDraw()

Discussion

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 on-screen if it is not hidden, it is attached to a view hierarchy in an NSWindow, and the NSWindow has a corresponding window device. An NSView can draw during printing if it is a descendant of the view being printed.

See Also

centerScanRect

Converts the corners of aRect to lie on the center of device pixels, which is useful in compensating for rendering overscanning when the coordinate system has been scaled.

public NSRect centerScanRect(NSRect aRect)

Discussion

This method converts the given rectangle to device coordinates, adjusts the rectangle to lie in the center of the pixels, and converts the resulting rectangle back to the receiver’s coordinate system. Returns the adjusted rectangle. Note that this method does not take into account any transformations performed using NSAffineTransform or Quartz 2D routines.

See Also

concludeDragOperation

public void concludeDragOperation(NSDraggingInfo draggingInfo)

Discussion

Invoked when the dragging operation is complete and the previous performDragOperation returned true. draggingInfo contains information about the operation. This method allows you to perform any tidying up that is needed, such as updating the visual representation now the dragged data has been incorporated. This message is the last message sent during a dragging session.

convertPointFromView

Converts aPoint from the coordinate system of aView to that of the receiver.

public NSPoint convertPointFromView(NSPoint aPoint, NSView aView)

Discussion

If aView is 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

convertPointToView

Converts aPoint from the receiver’s coordinate system to that of aView.

public NSPoint convertPointToView(NSPoint aPoint, NSView aView)

Discussion

If aView is 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

convertRectFromView

Converts aRect from the coordinate system of aView to that of the receiver.

public NSRect convertRectFromView(NSRect aRect, NSView aView)

Discussion

If aView is 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

convertRectToView

Converts aRect from the receiver’s coordinate system to that of aView.

public NSRect convertRectToView(NSRect aRect, NSView aView)

Discussion

If aView is 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

convertSizeFromView

Converts aSize from aView’s coordinate system to that of the receiver.

public NSSize convertSizeFromView(NSSize aSize, NSView aView)

Discussion

If aView is 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

convertSizeToView

Converts aSize from the receiver’s coordinate system to that of aView.

public NSSize convertSizeToView(NSSize aSize, NSView aView)

Discussion

If aView is 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

dataWithEPSInsideRect

Returns EPS data that draws the region of the receiver within aRect.

public NSData dataWithEPSInsideRect(NSRect aRect)

Discussion

This data can be placed on an NSPasteboard, written to a file, or used to create an NSImage object.

See Also

dataWithPDFInsideRect

Returns PDF data that draws the region of the receiver within aRect.

public NSData dataWithPDFInsideRect(NSRect aRect)

Discussion

This data can be placed on an NSPasteboard, written to a file, or used to create an NSImage object.

See Also

didAddSubview

Overridden by subclasses to perform additional actions when subviews are added to the receiver.

public void didAddSubview(NSView subview)

Discussion

Invoked by addSubview.

discardCursorRects

Invalidates all cursor rectangles set up using addCursorRect.

public void discardCursorRects()

Discussion

You need never invoke this method directly; it’s invoked automatically before the NSView’s cursor rectangles are reestablished using resetCursorRects.

See Also

display

Displays the receiver and all its subviews if possible, invoking each NSView’s lockFocus, drawRect, and unlockFocus methods as necessary.

public void display()

Discussion

If the receiver isn’t opaque, this method backs up the view hierarchy to the first opaque ancestor, calculates the portion of the opaque ancestor covered by the receiver, and begins displaying from there.

See Also

displayIfNeeded

Displays the receiver and all its subviews if any part of the receiver has been marked as needing display with a setNeedsDisplaymessage.

public void displayIfNeeded()

Discussion

This method invokes NSView’s lockFocus, drawRect, and unlockFocus methods as necessary. If the receiver isn’t opaque, this method backs up the view hierarchy to the first opaque ancestor, calculates the portion of the opaque ancestor covered by the receiver, and begins displaying from there.

See Also

displayIfNeededIgnoringOpacity

Acts as displayIfNeeded, except that this method doesn’t back up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

public void displayIfNeededIgnoringOpacity()

displayIfNeededInRect

Acts as displayIfNeeded, confining drawing to aRect.

public void displayIfNeededInRect(NSRect aRect)

Discussion

The argument you pass for aRect should be specified in the coordinate system of the receiver.

displayIfNeededInRectIgnoringOpacity

Acts as displayIfNeeded, but confining drawing to aRect and not backing up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

public void displayIfNeededInRectIgnoringOpacity(NSRect aRect)

Discussion

The argument you pass for aRect should be specified in the coordinate system of the receiver.

displayRect

Acts as display, confining drawing to aRect.

public void displayRect(NSRect aRect)

Discussion

The argument you pass for aRect should be specified in the coordinate system of the receiver.

displayRectIgnoringOpacity

Acts as display, but confining drawing to aRect and not backing up to the first opaque ancestor—it simply causes the receiver and its descendants to execute their drawing code.

public void displayRectIgnoringOpacity(NSRect aRect)

Discussion

The argument you pass for aRect should be specified in the coordinate system of the receiver.

dragFile

Initiates a dragging operation from the receiver, allowing the user to drag a file icon to any application that has window or view objects that accept files.

public boolean dragFile(String fullPath, NSRect aRect, boolean slideBack, NSEvent theEvent)

Discussion

This method must be invoked only within an implementation of the mouseDown method. Returns 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:

See the NSDraggingSource, NSDraggingInfo, and NSDraggingDestination interface specifications for more information on dragging operations.

See Also

draggingEntered

public int draggingEntered(NSDraggingInfo draggingInfo)

Discussion

Invoked when a dragged image enters the receiver. Specifically, this method is invoked when the mouse pointer enters the receiver’s bounds rectangle. draggingInfo contains information about the dragging operation.

Returns a value indicating which dragging operation will be performed when the image is released. In deciding which dragging operation to return, you should evaluate the overlap between both the dragging operations allowed by the source and the dragging operations and pasteboard data types the receiver supports. The returned value should be one of the following:

Option

Meaning

NSDraggingInfo.DragOperationCopy

The data represented by the image will be copied.

NSDraggingInfo.DragOperationLink

The data will be shared.

NSDraggingInfo.DragOperationGeneric

The operation will be defined by the destination.

NSDraggingInfo.DragOperationPrivate

The operation is negotiated privately between the source and the destination.

NSDraggingInfo.DragOperationEvery

Combines all the above.

If none of the operations is appropriate, returns NSDraggingInfo.DragOperationNone.

See Also

draggingExited

Invoked when the dragged image exits the receiver’s bounds rectangle.

public int draggingExited(NSDraggingInfo draggingInfo)

Discussion

draggingInfo contains information about the dragging operation.

draggingUpdated

public int draggingUpdated(NSDraggingInfo draggingInfo)

Discussion

Invoked periodically as the dragged image is held within the receiver. The messages continue until the image is either released or dragged out of the receiver. draggingInfo contains information about the dragging operation. Returns one of the dragging operation options listed under draggingEntered.

This method provides you with an opportunity to modify the dragging operation depending on the position of the mouse pointer inside of the receiver. For example, you may have several graphics or areas of text contained within the same view and wish to tailor the dragging operation, or to ignore the drag event completely, depending upon which object is underneath the mouse pointer at the time when the user releases the dragged image and performDragOperation is invoked.

You typically examine the contents of the pasteboard in draggingEntered, as this method is invoked only once, rather than in this method, which is invoked multiple times.

Only one view at a time receives a sequence of draggingUpdated messages. If the mouse pointer is within the bounds of two overlapping views that are both valid destinations, the uppermost view receives these messages until the image is either released or dragged out.

See Also

dragImage

Initiates a dragging operation from the receiver, allowing the user to drag arbitrary data with a specified icon into any application that has window or view objects that accept dragged data.

public void dragImage(NSImage anImage, NSPoint imageLoc, NSSize mouseOffset, NSEvent theEvent, NSPasteboard pboard, Object sourceObject, boolean slideBack)

Discussion

This method must be invoked only within an implementation of the mouseDown or mouseDragged methods.

The dragging operation uses these arguments:

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 interface specifications for more information on dragging operations.

See Also

dragPromisedFilesOfTypes

Initiates a dragging operation from the receiver, allowing the user to drag one or more promised files (or directories) into any application that has window or view objects that accept promised file data.

public boolean dragPromisedFilesOfTypes(NSArray typeArray, NSRect aRect, Object sourceObject, boolean slideBack, NSEvent theEvent)

Discussion

Returns true if the drag operation is initiated successfully. This method must be invoked only within an implementation of the mouseDown method. As part of its implementation, this method invokes dragImage.

Promised files are files that do not exist, yet, but that the drag source, sourceObject, promises to create at a file system location specified by the drag destination when the drag is successfully dropped.The dragging operation uses these arguments:

See “Drag and Drop” for more information on dragging operations.

Availability
See Also

drawPageBorderWithSize

Allows applications that use the Application Kit pagination facility to draw additional marks on each logical page, such as alignment marks or a virtual sheet border of size borderSize.

public void drawPageBorderWithSize(NSSize borderSize)

Discussion

The default implementation doesn’t draw anything.

See Also

drawRect

Overridden by subclasses to draw the receiver’s image within aRect.

public void drawRect(NSRect aRect)

Discussion

The receiver can assume the focus has been locked and the coordinate transformations of its frame and bounds rectangles have been applied; all it needs to do is invoke rendering client functions. aRect is a rectangle defining the area that the receiver is being asked to draw. On Mac OS X version 10.2 and earlier, the Application Kit automatically clips any drawing you perform in this method to this rectangle. On Mac OS X version 10.3 and later, the Application Kit automatically clips drawing to a list of non-overlapping rectangles that more rigorously specify the area needing drawing. You can invoke the rectsBeingDrawn method to retrieve this list of rectangles and use them to constrain your drawing more tightly, if you wish. Moreover, the needsToDrawRect method gives you a convenient way to test individual objects for intersection with the rectangles in the list. See “Drawing in a View” for information and references on drawing.

The default NSView implementation does nothing. If your custom view is a direct NSView subclass you do not need to call super's implementation. Note that it is the responsibility of each subclass to totally fill aRect if its superclass’ implementation actually draws and returns false from isOpaque.

See Also

drawSheetBorderWithSize

Allows applications that use the Application Kit pagination facility to draw additional marks on each printed sheet, such as crop marks or fold lines of size borderSize.

public void drawSheetBorderWithSize(NSSize borderSize)

Discussion

This method has been deprecated.

See Also

enclosingScrollView

Returns the nearest ancestor NSScrollView containing the receiver (not including the receiver itself); otherwise returns null.

public NSScrollView enclosingScrollView()

endPage

Writes the end of a conforming page.

public void endPage()

Discussion

This method is invoked after each page is printed. It invokes unlockFocus. This method also generates comments for the bounding box and page fonts, if they were specified as being at the end of the page.

focusRingType

Returns the type of focus ring drawn around the receiver.

public native int focusRingType()

Discussion

Possible values are listed in the “Constants” section of NSGraphics.You can disable a view’s drawing of its focus ring by overriding this method to return NSGraphics.FocusRingTypeNone, or by invoking setFocusRingType with and argument of NSGraphics.FocusRingTypeNone. You should only disable the default drawing of a view’s focus ring if you want it to draw its own focus ring (for example, setting the background color of the view), or if the view does not have sufficient space to display a focus ring.

Availability
See Also

frame

Returns the receiver’s frame rectangle, which defines its position in its superview.

public NSRect frame()

Discussion

The frame rectangle may be rotated; use the frameRotation method to check this.

See Also

frameRotation

Returns the angle, in degrees, of the receiver’s frame relative to its superview’s coordinate system.

public float frameRotation()

See Also

gState

Returns the identifier for the receiver’s graphics state object, or 0 if the receiver doesn’t have a graphics state object.

public int gState()

Discussion

A view object’s graphics state object is recreated from scratch whenever the view is focused, unless the allocateGState method has been invoked. So if the receiver hasn’t been focused or hasn’t received the allocateGState message, this method returns 0.

Although applications rarely need to use the value returned by gState, it can be passed to the few methods that take an object identifier as a parameter.

See Also

heightAdjustLimit

Returns the fraction (from 0.0 to 1.0) of the page that can be pushed onto the next page during automatic pagination to prevent items such as lines of text from being divided across pages.

public float heightAdjustLimit()

Discussion

This fraction is used to calculate the bottom edge limit for an adjustPageHeight message.

See Also

hitTest

Returns the farthest descendant of the receiver in the view hierarchy (including itself) that contains aPoint, or null if aPoint lies completely outside the receiver.

public NSView hitTest(NSPoint aPoint)

Discussion

aPoint is in the coordinate system of the receiver’s superview, not of the receiver itself. This method ignores hidden views.

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

inLiveResize

A convenience method, expected to be called from drawRect to make decisions about optimized drawing.

public boolean inLiveResize()

See Also

isDescendantOf

Returns true if the receiver is a subview, immediate or not, of aView, or if it’s identical to aView; otherwise returns false.

public boolean isDescendantOf(NSView aView)

See Also

isFlipped

Returns true if the receiver uses flipped drawing coordinates or false if it uses native coordinates.

public boolean isFlipped()

Discussion

NSView’s implementation returns false; subclasses that use flipped coordinates should override this method to return true.

isHidden

Returns whether the receiver is marked as hidden.

public boolean isHidden()

Discussion

The return value reflects the state of the receiver only, as set in Interface Builder or through the most recent setHidden message, and does not account for the state of the receiver’s ancestors in the view hierarchy, Thus this method returns false when the receiver is effectively hidden because it has a hidden ancestor. See setHidden for a discussion of the mechanics and implications of hidden views.

If you want to determine whether a view is effectively hidden, for whatever reason, send the isHiddenOrHasHiddenAncestor to the view instead.

Availability

isHiddenOrHasHiddenAncestor

Returns true if the receiver is marked as hidden or has an ancestor in the view hierarchy that is marked as hidden; returns false otherwise.

public boolean isHiddenOrHasHiddenAncestor()

Discussion

The return value reflects state set through the setHidden method in the receiver of one of its ancestors in the view hierarchy. It does not account for other reasons why a view might be considered hidden, such as being positioned outside its superview’s bounds, not having a window, or residing in a window that is offscreen or overlapped by another window.

Availability
See Also

isMouseInRect

Returns true if aRect contains aPoint (which represents the hot spot of the mouse cursor), accounting for whether the receiver is flipped or not.

public boolean isMouseInRect(NSPoint aPoint, NSRect aRect)

Discussion

aPoint and aRect must be expressed in the receiver’s coordinate system.

Point-in-rectangle functions generally assume that the bottom edge of a rectangle is outside of the rectangle boundaries, while the upper edge is inside the boundaries. This method views aRect from the point of view of the user—that is, this method always treats the bottom edge of the rectangle as the one closest to the bottom edge of the user’s screen. By making this adjustment, this function ensures consistent mouse-detection behavior from the user’s perspective.

See Also

isOpaque

Overridden by subclasses to return true if the receiver is opaque, false otherwise.

public boolean isOpaque()

Discussion

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

isRotatedFromBase

Returns true if the receiver or any of its ancestors has ever received a setFrameRotation or setBoundsRotation message; otherwise returns false.

public boolean isRotatedFromBase()

Discussion

The 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 0, this method still returns true.

See Also

isRotatedOrScaledFromBase

Returns true if the receiver or any of its ancestors has ever had a nonzero frame or bounds rotation, or has been scaled from the window’s base coordinate system; otherwise returns false.

public boolean isRotatedOrScaledFromBase()

Discussion

The 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 0, this method still returns true.

See Also

knowsPageRange

Returns true if the receiver handles page boundaries.

public boolean knowsPageRange(NSMutableRange aRange)

Discussion

Returns false if the receiver uses NSView’s default auto-pagination mechanism. If it returns true, the page range is returned in aRange. Page numbers are one-based, that is pages run from one to N.

The default implementation returns false. Override this method if your class handles page boundaries.

locationOfPrintRect

Invoked by print to determine the location of aRect, the rectangle being printed on the physical page.

public NSPoint locationOfPrintRect(NSRect aRect)

Discussion

The return value of this method is used to set the origin for aRect, whose size the receiver can examine in order to properly place it. Both the rectangle and the returned location are expressed in the default coordinate system of the page.

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.

lockFocus

Locks the focus on the receiver, so subsequent commands take effect in the receiver’s window and coordinate system.

public void lockFocus()

Discussion

If you don’t use a display... method to draw an NSView, you must invoke lockFocus before invoking methods that send commands to the window server, and must balance it with an unlockFocus message when finished.

See Also

menuForEvent

Overridden by subclasses to return a context-sensitive pop-up menu for the mouse-down event theEvent.

public NSMenu menuForEvent(NSEvent theEvent)

Discussion

The receiver can use information in the mouse event, such as its location over a particular element of the receiver, to determine what kind of menu to return. For example, a text object might display a text-editing menu when the cursor lies over text and a menu for changing graphics attributes when the cursor lies over an embedded image.

NSView’s implementation returns the receiver’s normal menu.

See Also

mouseDownCanMoveWindow

Returns true if the receiver does not need to handle a mouse down and can pass it through to the view; false if it needs to handle the mouse down.

public boolean mouseDownCanMoveWindow()

Discussion

This allows iApp-type applications to properly determine the region by which a window can be moved. By default, this method returns false if the view is opaque; otherwise, it returns true. Subclasses can override this method to return a different value.

Availability

needsDisplay

Returns true if the receiver needs to be displayed, as indicated using setNeedsDisplay; returns false otherwise.

public boolean needsDisplay()

Discussion

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.

needsPanelToBecomeKey

Overridden by subclasses to return 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.

public boolean needsPanelToBecomeKey()

Discussion

Such a subclass should also override acceptsFirstResponder to return true. NSView’s implementation returns false.

See Also

needsToDrawRect

Returns whether rectangle aRect intersects any part of the area that the receiver is being asked to draw.

public boolean needsToDrawRect(NSRect aRect)

Discussion

You typically send this message from within a drawRect implementation. It gives you a convenient way to determine whether any part of a given graphical entity might need to be drawn. It is optimized to efficiently reject any rectangle that lies outside the bounding box of the area the receiver is being asked to draw in drawRect.

Availability

nextKeyView

Returns the view object following the receiver in the key view loop, or null if there is none.

public NSView nextKeyView()

Discussion

This view should, if possible, be made first responder when the user navigates forward from the receiver using keyboard interface control.

See Also

nextValidKeyView

Returns the closest view object in the key view loop that follows the receiver and actually accepts first responder status, or null if there is none.

public NSView nextValidKeyView()

Discussion

This method ignores hidden views when it determines the next valid key view.

See Also

opaqueAncestor

Returns the receiver’s closest opaque ancestor (including the receiver itself).

public NSView opaqueAncestor()

See Also

performDragOperation

public boolean performDragOperation(NSDraggingInfo draggingInfo)

Discussion

Invoked after the released image has been removed from the screen and the previous prepareForDragOperation message has returned true. draggingInfo contains information about the dragging operation. This method should do the real work of importing the pasteboard data represented by the image. If the receiver accepts the data, returns true, otherwise returns false.

See Also

performKeyEquivalent

Implemented by subclasses to respond to key equivalents (also known as shortcuts).

public boolean performKeyEquivalent(NSEvent theEvent)

Discussion

If the receiver’s key equivalent is the same as the characters of the key-down event theEvent, as returned by charactersIgnoringModifiers, it should take the appropriate action and return 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

Implemented by subclasses to respond to mnemonics.

public boolean performMnemonic(String aString)

Discussion

If the receiver’s mnemonic is the same as the characters of the string aString, it should take the appropriate action and return 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. Mnemonics are not supported in Mac OS X.

See Also

postsBoundsChangedNotifications

Returns true if the receiver posts notifications to the default notification center whenever its bounds rectangle changes; returns false otherwise.

public boolean postsBoundsChangedNotifications()

Discussion

See setPostsBoundsChangedNotifications for a list of methods that result in notifications.

postsFrameChangedNotifications

Returns true if the receiver posts notifications to the default notification center whenever its frame rectangle changes; returns false otherwise.

public boolean postsFrameChangedNotifications()

Discussion

See setPostsBoundsChangedNotifications for a list of methods that result in notifications.

prepareForDragOperation

public boolean prepareForDragOperation(NSDraggingInfo draggingInfo)

Discussion

Invoked when the image is released, if the most recent draggingEntered or draggingUpdated message returned an acceptable drag-operation value. draggingInfo contains information about the dragging operation. Returns true if the receiver agrees to perform the drag operation and false if not.

See Also

preservesContentDuringLiveResize

Returns true if the view supports the optimization of live resize operations by preserving content that has not moved; otherwise, returns false.

public boolean preservesContentDuringLiveResize()

Discussion

The default is false. If your view supports the content preservation feature, you should override this method and have your implementation return true.

Content preservation lets your view decide what to redraw during a live resize operation. If your view supports this feature, you should also provide a custom implementation of setFrameSize that invalidates the portions of your view that actually need to be redrawn.

For information on how to implement this feature in your views, see Cocoa Performance Guidelines.

Availability
See Also

previousKeyView

Returns the view object preceding the receiver in the key view loop, or null if there is none.

public NSView previousKeyView()

Discussion

This view should, if possible, be made first responder when the user navigates backward from the receiver using keyboard interface control.

See Also

previousValidKeyView

Returns the closest view object in the key view loop that precedes the receiver and actually accepts first responder status, or null if there is none.

public NSView previousValidKeyView()

Discussion

This method ignores hidden views when it determines the previous valid key view.

See Also

print

This action method opens the Print panel, and if the user chooses an option other than canceling, prints the receiver and all its subviews to the device specified in the Print panel.

public void print(Object sender)

See Also

rectForPage

Implemented by subclasses to determine the portion of the receiver to be printed for the page number page.

public NSRect rectForPage(int pageNumber)

Discussion

If the receiver responded true to an earlier knowsPageRange 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. Page numbers are one-based, that is pages run from one to N. This method returns NSRect.ZeroRect if pageNumber is outside the receiver’s bounds.

If an NSView responds false to knowsPageRange, this method isn’t invoked by the printing mechanism.

See Also

rectPreservedDuringLiveResize

Returns the rectangle identifying the portion of your view that did not change during a live resize operation.

public NSRect rectPreservedDuringLiveResize()

Discussion

The returned rectangle is in the coordinate system of your view and reflects the space your view previously occupied. This rectangle may be smaller or the same size as your view’s current bounds, depending on whether the view grew or shrunk.

If your view does not support content preservation during live resizing, the returned rectangle will be empty. To support content preservation, override preservesContentDuringLiveResize in your view and have your implementation return true.

Note: The window containing your view must also support content preservation. To enable support for this feature in your window, use the setPreservesContentDuringLiveResize: method of NSWindow.

Availability
See Also

rectsBeingDrawn

Returns a list of non-overlapping rectangles that define the area the receiver is being asked to draw in drawRect.

public NSArray rectsBeingDrawn()

Discussion

An implementation of drawRect can use this information to test whether objects or regions within the view intersect with the rectangles in the list, and thereby avoid unnecessary drawing that would be completely clipped away.

The needsToDrawRect method gives you a convenient way to test individual objects for intersection with the area being drawn in drawRect. However, you may want to retrieve and directly inspect the rectangle list if this is a more efficient way to perform intersection testing.

You should send this message only from within a drawRect implementation. The aRect parameter of drawRect is the rectangle enclosing the returned list of rectangles; you can use it in an initial pass to reject objects that are clearly outside the area to be drawn.

Availability
See Also

rectsExposedDuringLiveResize

Returns a list of rectangles indicating the newly exposed areas of the receiver.

public NSArray rectsExposedDuringLiveResize()

Discussion

The returned rectangles are in the coordinate space of the receiver. If your view does not support content preservation during live resizing, the entire area of your view is returned. To support content preservation, override preservesContentDuringLiveResize in your view and have your implementation return true.

Note: The window containing your view must also support content preservation. To enable support for this feature in your window, use the setPreservesContentDuringLiveResize: method of NSWindow.

If the view decreased in both height and width, the list of returned rectangles will be empty. If the view increased in both height and width and its upper-left corner stayed anchored in the same position, the list of returned rectangles will contain a vertical and horizontal component indicating the exposed area.

Availability
See Also

reflectScrolledClipView

Notifies aClipView’s superview that either aClipView’s bounds rectangle or the document view’s frame rectangle has changed, and that any indicators of the scroll position need to be adjusted.

public void reflectScrolledClipView(NSClipView aClipView)

Discussion

NSScrollView implements this method to update its NSScrollers.

registerForDraggedTypes

Registers pboardTypes as the pasteboard types that the receiver will accept as the destination of an image-dragging session.

public void registerForDraggedTypes(NSArray pboardTypes)

Discussion

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 interface methods. As a convenience, NSView provides default implementations of these methods. See the NSDraggingDestination interface specification for details.

See Also

releaseGState

Frees the receiver’s graphics state object, if it has one.

public void releaseGState()

See Also

removeCursorRect

Completely removes a cursor rectangle from the receiver.

public void removeCursorRect(NSRect aRect, NSCursor aCursor)

Discussion

aRect and aCursor must match values previously specified using addCursorRect.

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

removeFromSuperview

Unlinks the receiver from its superview and its NSWindow, removes it from the responder chain, and invalidates its cursor rectangles.

public void removeFromSuperview()

Discussion

Never invoke this method during display.

See Also

removeFromSuperviewWithoutNeedingDisplay

Unlinks the receiver from its superview and its NSWindow, removes it from the responder chain, but does not invalidate its cursor rectangles to cause redrawing.

public void removeFromSuperviewWithoutNeedingDisplay()

Discussion

Unlike its counterpart, removeFromSuperview, this method can be safely invoked during display.

See Also

removeTrackingRect

Removes the tracking rectangle identified by aTag, which is the value returned by a previous addTrackingRect message.

public void removeTrackingRect(int aTag)

renewGState

Invalidates the receiver’s graphics state object, if it has one, so it will be regenerated using setUpGState the next time the receiver is focused for drawing.

public void renewGState()

See Also

replaceSubview

Replaces oldView with newView in the receiver’s subviews.

public void replaceSubview(NSView oldView, NSView newView)

Discussion

Does nothing if oldView is not a subview of the receiver.

Neither oldView nor newView may be null, and the behavior is undefined if either of these parameters is null.

See Also

resetCursorRects

Overridden by subclasses to define their default cursor rectangles.

public void resetCursorRects()

Discussion

A subclass’s implementation must invoke addCursorRect for each cursor rectangle it wants to establish. NSView’s implementation does nothing.

Application code should never invoke this method directly; it’s invoked automatically as described in “Handling Tracking-Rectangle and Cursor-Update Events in Views”. Use the invalidateCursorRectsForView method instead to explicitly rebuild cursor rectangles.

See Also

resizeSubviewsWithOldSize

Informs the receivers’s subviews that the receiver’s bounds rectangle size has changed from oldBoundsSize.

public void resizeSubviewsWithOldSize(NSSize oldBoundsSize)

Discussion

If the receiver is configured to autoresize its subviews, this method is automatically invoked by any method that changes the receiver’s frame size.

NSView’s implementation sends resizeWithOldSuperviewSize to the receiver’s subviews with oldBoundsSize as the argument. You shouldn’t invoke this method directly, but you can override it to define a specific retiling behavior.

See Also

resizeWithOldSuperviewSize

Informs the receiver that the bounds size of its superview has changed from oldBoundsSize.

public void resizeWithOldSuperviewSize(NSSize oldBoundsSize)

Discussion

This method is normally invoked automatically from resizeSubviewsWithOldSize.

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.

rotateByAngle

Rotates the receiver’s bounds rectangle by angle degrees around the origin of the coordinate system, (0.0, 0.0).

public void rotateByAngle(float angle)

Discussion

See the setBoundsRotation method description for more information. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See Also

scaleUnitSquareToSize

Scales the receiver’s coordinate system so that the unit square scales to newUnitSize.

public void scaleUnitSquareToSize(NSSize newUnitSize)

Discussion

For example, a newUnitSize of (0.5, 1.0) causes the receiver’s horizontal coordinates to be halved, in turn doubling the width of its bounds rectangle. Note that scaling is performed from the origin of the coordinate system, (0.0, 0.0), not the origin of the bounds rectangle; as a result, both the origin and size of the bounds rectangle are changed. The frame rectangle remains unchanged.

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See Also

scrollClipViewToPoint

Notifies the superview of aClipView that aClipView needs to set its bounds rectangle origin to newOrigin.

public void scrollClipViewToPoint(NSClipView aClipView, NSPoint newOrigin)

Discussion

The superview of aClipView should then send a scrollToPoint message to aClipView with newOrigin as the argument. This mechanism is provided so the NSClipView’s superview can coordinate scrolling of multiple tiled NSClipViews.

See Also

scrollPoint

Scrolls the receiver’s closest ancestor NSClipView so aPoint in the receiver lies at the origin of the NSClipView’s bounds rectangle.

public void scrollPoint(NSPoint aPoint)

See Also

scrollRect

Copies the visible portion of the receiver’s rendered image within aRect and lays that portion down again at offset from aRect’s origin.

public void scrollRect(NSRect aRect, NSSize offset)

Discussion

This method is useful during scrolling or translation of the coordinate system to efficiently move as much of the receiver’s rendered image as possible without requiring it to be redrawn, following these steps:

  1. Invoke scrollRect to copy the rendered image.

  2. Move the view object’s origin or scroll it within its superview.

  3. Calculate the newly exposed rectangles and invoke setNeedsDisplay to draw them.

You should rarely need to use this method, however. The scrollPoint, scrollRectToVisible, and autoscroll methods automatically perform optimized scrolling.

See Also

scrollRectToVisible

Scrolls the receiver’s closest ancestor NSClipView the minimum distance needed so aRect in the receiver becomes visible in the NSClipView.

public boolean scrollRectToVisible(NSRect aRect)

Discussion

Returns true if any scrolling is performed; otherwise returns false.

See Also

setAutoresizesSubviews

Determines whether the receiver automatically resizes its subviews when its frame size changes.

public void setAutoresizesSubviews(boolean flag)

Discussion

If flag is 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

setAutoresizingMask

Determines how the receiver’s resizeWithOldSuperviewSize method changes its frame rectangle.

public void setAutoresizingMask(int mask)

Discussion

mask can be specified by combining any of the following options using the C bitwise OR operator:

Option

Meaning

ViewNotSizable

The receiver cannot be resized.

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

setBounds

Sets the receiver’s bounds rectangle to boundsRect.

public void setBounds(NSRect boundsRect)

Discussion

The bounds rectangle determines the origin and scale of the receiver’s coordinate system within its frame rectangle. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

After calling this method, NSView creates an internal transform (or appends these changes to an existing internal transform) to convert from frame coordinates to bounds coordinates in your view. As long as the width-to-height ratio of the two coordinate systems remains the same, your content appears normal. If the ratios differ, your content may appear skewed.

See Also

setBoundsOrigin

Sets the origin of the receiver’s bounds rectangle to newOrigin, effectively shifting its coordinate system so newOrigin lies at the origin of the receiver’s frame rectangle.

public void setBoundsOrigin(NSPoint newOrigin)

Discussion

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

After calling this method, NSView creates an internal transform (or appends these changes to an existing internal transform) to convert from frame coordinates to bounds coordinates in your view. As long as the width-to-height ratio of the two coordinate systems remains the same, your content appears normal. If the ratios differ, your content may appear skewed.

See Also

setBoundsRotation

Sets the rotation of the receiver’s bounds rectangle to angle degrees.

public void setBoundsRotation(float angle)

Discussion

Positive values indicate counterclockwise rotation, negative clockwise. Rotation is performed around the coordinate system origin, (0.0, 0.0), which need not coincide with that of the frame rectangle or the bounds rectangle. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification 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 coordinate system in the drawRect method rather than use this method.

After calling this method, NSView creates an internal transform (or appends these changes to an existing internal transform) to convert from frame coordinates to bounds coordinates in your view. As long as the width-to-height ratio of the two coordinate systems remains the same, your content appears normal. If the ratios differ, your content may appear skewed.

See Also

setBoundsSize

Sets the size of the receiver’s bounds rectangle to newSize, inversely scaling its coordinate system relative to its frame rectangle.

public void setBoundsSize(NSSize newSize)

Discussion

For example, a view object with a frame size of (100.0, 100.0) and a bounds size of (200.0, 100.0) draws half as wide along the x axis. This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

After calling this method, NSView creates an internal transform (or appends these changes to an existing internal transform) to convert from frame coordinates to bounds coordinates in your view. As long as the width-to-height ratio of the two coordinate systems remains the same, your content appears normal. If the ratios differ, your content may appear skewed.

See Also

setFocusRingType

Sets the type of focus ring to be drawn around the receiver.

public native void setFocusRingType(int focusRingType)

Discussion

Possible values are listed in the “Constants” section of NSGraphics.You can specify NSGraphics.FocusRingTypeNone to indicate you do not want your view to have a focus ring.

Note: This method only sets the desired focus ring type and does not cause the view to draw the actual focus ring. You are responsible for drawing the focus ring in your view’s drawRect: method whenever your view is made the first responder.

Availability
See Also

setFrame

Sets the receiver’s frame rectangle to frameRect, thereby repositioning and resizing it within the coordinate system of its superview.

public void setFrame(NSRect frameRect)

Discussion

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts aViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

If your view does not use a custom bounds rectangle, this method also sets your view bounds to match the size of the new frame. You specify a custom bounds rectangle by calling setBounds, setBoundsOrigin, setBoundsRotation, or setBoundsSizeexplicitly. Once set, NSView creates an internal transform to convert from frame coordinates to bounds coordinates. As long as the width-to-height ratio of the two coordinate systems remains the same, your content appears normal. If the ratios differ, your content may appear skewed.

See Also

setFrameOrigin

Sets the origin of the receiver’s frame rectangle to newOrigin, effectively repositioning it within its superview.

public void setFrameOrigin(NSPoint newOrigin)

Discussion

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts aViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See Also

setFrameRotation

Sets the rotation of the receiver’s frame rectangle to angle degrees, rotating it within its superview without affecting its coordinate system.

public void setFrameRotation(float angle)

Discussion

Positive values indicate counterclockwise rotation, negative clockwise. Rotation is performed around the origin of the frame rectangle.

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

See Also

setFrameSize

Sets the size of the receiver’s frame rectangle to newSize, resizing it within its superview without affecting its coordinate system.

public void setFrameSize(NSSize newSize)

Discussion

This method neither redisplays the receiver nor marks it as needing display. You must do this yourself with display or setNeedsDisplay.

This method posts a ViewFrameDidChangeNotification to the default notification center if the receiver is configured to do so.

In Mac OS X version 10.4 and later, you can override this method to support content preservation during live resizing. In your overridden implementation, include some conditional code to be executed only during a live resize operation. Your code must invalidate any portions of your view that need to be redrawn.

See Also

setHidden

Sets whether the receiver is hidden.

public void setHidden(boolean flag)

Discussion

A hidden view disappears from its window and does not receive input events. It remains in its superview’s list of subviews, however, and participates in autoresizing as usual. The Application Kit also disables any cursor rectangle, tool-tip rectangle, or tracking rectangle associated with a hidden view. Hiding a view with subviews has the effect of hiding those subviews and any view descendents they might have. This effect is implicit and does not alter the hidden state of the receiver’s descendents as reported by isHidden.

Hiding the view that is the window’s current first responder causes the view’s next valid key view (nextValidKeyView) to become the new first responder. A hidden view remains in the nextKeyView chain of views it was previously part of, but is ignored during keyboard navigation.

Availability
See Also

setKeyboardFocusRingNeedsDisplayInRect

Invalidates the area around the focus ring.

public void setKeyboardFocusRingNeedsDisplayInRect(NSRect rect)

Discussion

rect is the rectangle of the control or cell. rect will be expanded to include the focus ring for invalidation.

setNeedsDisplay

If flag is true, marks the receiver’s entire bounds as needing display; if flag is false, marks it as not needing display.

public void setNeedsDisplay(boolean aFlag)

Discussion

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.)

Marks the region of the receiver within invalidRect as needing display, increasing the receiver’s existing invalid region to include it.

public void setNeedsDisplay(NSRect invalidRect)

Discussion

A later displayIfNeeded... method will then perform drawing only within the invalid region. 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.)

See Also

setNextKeyView

Inserts aView after the receiver in the key view loop of the receiver’s NSWindow.

public void setNextKeyView(NSView aView)

See Also

setPostsBoundsChangedNotifications

Controls whether the receiver informs observers when its bounds rectangle changes.

public void setPostsBoundsChangedNotifications(boolean flag)

Discussion

If flag is true, the receiver will post notifications to the default notification center whenever its bounds rectangle changes; if flag is false it won’t. Note that if flag is true and bounds notifications are suppressed, when the bounds change notification is reenabled the view will immediately post a single such notification if its bounds changed during this time. This will happen even if there has been no net change in the view's bounds.

The following methods can result in notification posting:

See Also

setPostsFrameChangedNotifications

Controls whether the receiver informs observers when its frame rectangle changes.

public void setPostsFrameChangedNotifications(boolean flag)

Discussion

If flag is true, the receiver will post notifications to the default notification center whenever its frame rectangle changes; if flag is false it won’t.Note that if flag is true and frame notifications are suppressed, when the frame change notification is reenabled the view will immediately post a single such notification if its frame changed during this time. This will happen even if there has been no net change in the view's frame.

The following methods can result in notification posting:

See Also

setToolTip

Sets the tool tip text for the view to string.

public void setToolTip(String string)

Discussion

If string is null, cancels tool tip display for the view.

See Also

setUpGState

Overridden by subclasses to (re)initialize the receiver’s graphics state object.

public void setUpGState()

Discussion

This method is automatically invoked when the graphics state object created using allocateGState needs to be initialized. NSView’s implementation does nothing. Your subclass can override it to set the current font, line width, or any other graphics state parameter except coordinate transformations and the clipping path—these are established by the frame and bounds rectangles and by methods such as scaleUnitSquareToSize and translateOriginToPoint. Note that drawRect: can further transform the coordinate system and clipping path for whatever temporary effects it needs.

See Also

shouldDelayWindowOrderingForEvent

Overridden by subclasses to allow the user to drag images from the receiver without its window moving forward and possibly obscuring the destination and without activating the application.

public boolean shouldDelayWindowOrderingForEvent(NSEvent theEvent)

Discussion

If this method returns 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 occur. 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 NSApplication.sharedApplication(), 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.

shouldDrawColor

Returns 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.

public boolean shouldDrawColor()

Discussion

An NSView can base its drawing behavior on the return value of this method to improve its appearance in grayscale windows.

See Also

subviews

Return the receiver’s immediate subviews.

public NSArray subviews()

Discussion

The order of the subviews may be considered as being back-to-front, but this does not imply invalidation and drawing behavior. The order is based on the order of the receiver's subviews as specified in the nib file from which they were unarchived or the programmatic interface for modifying the receiver's subview list. This ordering is also the reverse of the order in which hit-testing is done.

See Also

superview

Returns the receiver’s superview, or null if it has none.

public NSView superview()

Discussion

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

tag

Returns the receiver’s tag, an integer that you can use to identify view objects in your application.

public int tag()

Discussion

NSView’s implementation returns –1. Subclasses can override this method to provide individual tags, possibly adding storage and a setTag method (which NSView doesn’t define).

See Also

toolTip

Returns the text for the view’s tool tip.

public String toolTip()

Discussion

Returns null if the view doesn’t currently display tool tip text.

See Also

translateOriginToPoint

Translates the receiver’s coordinate system so that its origin moves to newOrigin.

public void translateOriginToPoint(NSPoint newOrigin)

Discussion

In the process, the origin of the receiver’s bounds rectangle is shifted by (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 a ViewBoundsDidChangeNotification to the default notification center if the receiver is configured to do so.

See Also

unlockFocus

Balances an earlier lockFocus message; restoring the focus to the previously focused view is necessary.

public void unlockFocus()

Discussion

Throws an InvalidArgumentException if invoked on the wrong view.

See Also

unregisterDraggedTypes

Unregisters the receiver as a possible destination in a dragging session.

public void unregisterDraggedTypes()

See Also

viewDidEndLiveResize

Informs the receiver of the end of a live resize.

public void viewDidEndLiveResize()

Discussion

In the simple case, a view is sent viewWillStartLiveResize before the first resize operation on the containing window and viewDidEndLiveResize after the last resize operation. A view that is repeatedly added and removed from a window during live resize will receive only one viewWillStartLiveResize (on the first time it is added to the window) and one viewDidEndLiveResize (when the window has completed the live resize operation). This allows a superview such as NSBrowser to add and remove its NSMatrix subviews during live resize without the NSMatrix receiving multiple calls to these methods.

A view might allocate data structures to cache-drawing information in viewWillStartLiveResize and should clean up these data structures in viewDidEndLiveResize. In addition, a view that does optimized drawing during live resize might want to do full drawing after viewDidEndLiveResize, although a view should not assume that it has a drawing context in viewDidEndLiveResize (since it may have been removed from the window during live resize). A view that wants to redraw itself after live resize should call setNeedsDisplay(true) in viewDidEndLiveResize.

A view subclass should call super from these methods.

See Also

viewDidMoveToSuperview

Informs the receiver that its superview has changed (possibly to null).

public void viewDidMoveToSuperview()

Discussion

The default implementation does nothing; subclasses can override this method to perform whatever actions are necessary.

See Also

viewDidMoveToWindow

Informs the receiver that it has been added to a new view hierarchy.

public void viewDidMoveToWindow()

Discussion

The default implementation does nothing; subclasses can override this method to perform whatever actions are necessary.

window may return null when this method is invoked, indicating that the receiver does not currently reside in any window. This occurs when the receiver has just been removed from its superview or when the receiver has just been added to a superview that does not itself have a window. Overrides of this method may choose to ignore such cases if they are not of interest.

See Also

viewWillMoveToSuperview

Informs the receiver that its superview is about to change to newSuperview (which may be null).

public void viewWillMoveToSuperview(NSView newSuperview)

Discussion

Subclasses can override this method to perform whatever actions are necessary.

See Also

viewWillMoveToWindow

Informs the receiver that it’s being added to the view hierarchy of newWindow (which may be null).

public void viewWillMoveToWindow(NSWindow newWindow)

Discussion

Subclasses can override this method to perform whatever actions are necessary.

See Also

viewWillStartLiveResize

Informs the receiver of the start of a live resize.

public void viewWillStartLiveResize()

Discussion

In the simple case, a view is sent viewWillStartLiveResize before the first resize operation on the containing window and viewDidEndLiveResize after the last resize operation. A view that is repeatedly added and removed from a window during live resize will receive only one viewWillStartLiveResize (on the first time it is added to the window) and one viewDidEndLiveResize (when the window has completed the live resize operation). This allows a superview such as NSBrowser to add and remove its NSMatrix subviews during live resize without the NSMatrix receiving multiple calls to these methods.

A view might allocate data structures to cache-drawing information in viewWillStartLiveResize and should clean up these data structures in viewDidEndLiveResize. In addition, a view that does optimized drawing during live resize might want to do full drawing after viewDidEndLiveResize, although a view should not assume that it has a drawing context in viewDidEndLiveResize (since it may have been removed from the window during live resize). A view that wants to redraw itself after live resize should call setNeedsDisplay(true) in viewDidEndLiveResize.

A view subclass should call super from these methods.

See Also

viewWithTag

Returns the receiver’s nearest descendant (including itself) whose tag is aTag, or null if no subview has that tag.

public NSView viewWithTag(int aTag)

See Also

visibleRect

Returns the portion of the receiver not clipped by its superviews.

public NSRect visibleRect()

Discussion

Visibility is therefore defined quite simply and doesn’t account for whether other NSViews (or windows) overlap the receiver or whether the receiver has a window at all. This method returns NSRect.ZeroRect if the receiver is effectively hidden.

During a printing operation the visible rectangle is further clipped to the page being imaged.

See Also

wantsDefaultClipping

Returns whether the Application Kit’s default clipping provided to drawRect implementations is in effect.

public boolean wantsDefaultClipping()

Discussion

By default, this method returns true. Subclasses may override this method to return false if they want to suppress the default clipping. They may want to do this in situations where drawing performance is critical to avoid the cost of setting up, enforcing, and cleaning up the clip path

A view that overrides this method to refuse the default clipping must either set up whatever clipping it requires or constrain its drawing exactly to the list of rectangles returned by rectsBeingDrawn. Failing to do so could result in corruption of other drawing in the view’s window.

Availability

widthAdjustLimit

Returns the fraction (from 0.0 to 1.0) of the page that can be pushed onto the next page during automatic pagination to prevent items such as small images or text columns from being divided across pages.

public float widthAdjustLimit()

Discussion

This fraction is used to calculate the right edge limit for a adjustPageWidth message.

See Also

willRemoveSubview

Overridden by subclasses to perform additional actions before subviews are removed from the receiver.

public void willRemoveSubview(NSView subview)

Discussion

Invoked when subview receives a removeFromSuperview message or subview is removed from the receiver due to it being added to another view with addSubview.

window

Returns the receiver’s window object, or null if it has none.

public NSWindow window()

See Also

writeEPSInsideRectToPasteboard

Writes EPS data that draws the region of the receiver within aRect onto pboard.

public void writeEPSInsideRectToPasteboard(NSRect aRect, NSPasteboard pboard)

See Also

writePDFInsideRectToPasteboard

Writes PDF data that draws the region of the receiver within aRect onto pboard.

public void writePDFInsideRectToPasteboard(NSRect aRect, NSPasteboard pboard)

See Also

Constants

NSView defines the following constants to be used when specifying a view’s border:

Constant

Description

BezelBorder

A concave border that makes the view look sunken.

GrooveBorder

A thin border that looks etched around the image.

LineBorder

A black line border around the view.

NoBorder

No border.

Notifications

ViewBoundsDidChangeNotification

Posted whenever the NSView’s bounds rectangle changes independently of the frame rectangle, if the NSView is configured using setPostsBoundsChangedNotifications to post such notifications.

The notification object is the NSView whose bounds rectangle has changed. This notification does not contain a userInfo dictionary.

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.

ViewFocusDidChangeNotification

Deprecated notification that was posted for an NSView and each of its descendents (recursively) whenever the frame or bounds geometry of the view changed.

In Mac OS X v10.4 and later, this notification is no longer posted. In earlier version of Mac OS X, use NSViewBoundsDidChangeNotification and NSViewFrameDidChangeNotification instead to get the same information provided by this notification.

The notification object is the NSView whose geometry changed. This notification does not contain a userInfo dictionary.

Availability
See Also

ViewFrameDidChangeNotification

Posted whenever the NSView’s frame rectangle changes, if the NSView is configured using setPostsFrameChangedNotifications to post such notifications.

The notification object is the NSView whose frame rectangle has changed. This notification does not contain a userInfo dictionary.

The following methods can result in notification posting:



Next Page > Hide TOC


© 1997, 2007 Apple Inc. All Rights Reserved. (Last updated: 2007-02-01)


Did this document help you?
Yes: Tell us what works for you.
It’s good, but: Report typos, inaccuracies, and so forth.
It wasn’t helpful: Tell us what would have helped.