Class

NSView

An NSView object provides the infrastructure for drawing, printing, and handling events in an app. You typically don’t use NSView objects directly. Instead, you use objects whose classes descend from NSView or you subclass NSView yourself and override its methods to implement the behavior you need. An instance of the NSView class (or one of its subclasses) is commonly known as a view object, or simply as a view.

Overview

Views handle the presentation and interaction with your app’s visible content. You arrange one or more views inside an NSWindow object, which acts as a wrapper for your content. A view object defines a rectangular region for drawing and receiving mouse events. Views handle other chores as well, including the dragging of icons and working with the NSScrollView class to support efficient scrolling.

Most of the functionality of the NSView class is automatically invoked by AppKit. 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. For any view, there are many methods that you can use as-is. The following methods are commonly used.

  • frame returns the location and size of the NSView object.

  • bounds returns the internal origin and size of the NSView object.

  • needsDisplay determines whether the NSView object needs to be redrawn.

  • window returns the NSWindow object that contains the NSView object.

  • draw(_:) draws the NSView object. (All subclasses must implement this method, but it’s rarely invoked explicitly.)

For more information on how NSView instances handle event and action messages, see Cocoa Event Handling Guide. For more information on displaying tooltips and contextual menus, see Displaying Contextual Menus and Managing Tooltips.

Subclassing Notes

NSView is perhaps the most important class in AppKit 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 Cocoa Drawing Guide and Cocoa Event Handling Guide (especially "Handling Mouse Events" and "Mouse Events").

Handling Events in Your Subclass

If you subclass NSView directly and handle specific types of events, the implementation of your event-related methods should generally not call super. Views inherit their event-handling capabilities from their NSResponder parent class. The default behavior for responders is to pass events up the responder chain, which is not the behavior you typically want if you handle events in a custom view. Therefore, you should not call super if your view implements any of the following methods and handles the event:

If your view descends from a class other than NSView, call super to let the parent view handle any events that you do not.

Symbols

Creating Instances

init(frame: NSRect)

Initializes and returns a newly allocated NSView object with a specified frame rectangle.

func prepareForReuse()

Restores the view to an initial state so that it can be reused.

Managing the View Hierarchy

var superview: NSView?

The view that is the parent of the current view.

var subviews: [NSView]

The array of views embedded in the current view.

var window: NSWindow?

The view’s window object, if it is installed in a window.

func addSubview(NSView)

Adds a view to the view’s subviews so it’s displayed above its siblings.

func addSubview(NSView, positioned: NSWindowOrderingMode, relativeTo: NSView?)

Inserts a view among the view’s subviews so it’s displayed immediately above or below another view.

func didAddSubview(NSView)

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

func removeFromSuperview()

Unlinks the view from its superview and its window, removes it from the responder chain, and invalidates its cursor rectangles.

func removeFromSuperviewWithoutNeedingDisplay()

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

func replaceSubview(NSView, with: NSView)

Replaces one of the view’s subviews with another view.

func isDescendant(of: NSView)

Returns true if the view is a subview of a given view or if it’s identical to that view; otherwise, it returns false.

var opaqueAncestor: NSView?

The view’s closest opaque ancestor, which might be the view itself.

func ancestorShared(with: NSView)

Returns the closest ancestor shared by the view and another specified view.

func viewDidMoveToSuperview()

Informs the view that its superview has changed (possibly to nil).

func viewDidMoveToWindow()

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

func viewWillMove(toSuperview: NSView?)

Informs the view that its superview is about to change to the specified superview (which may be nil).

func viewWillMove(toWindow: NSWindow?)

Informs the view that it’s being added to the view hierarchy of the specified window object (which may be nil).

func willRemoveSubview(NSView)

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

var enclosingMenuItem: NSMenuItem?

The menu item containing the view or any of its superviews in the view hierarchy.

Modifying the Frame Rectangle

var frame: NSRect

The view’s frame rectangle, which defines its position and size in its superview’s coordinate system.

func setFrameOrigin(NSPoint)

Sets the origin of the view’s frame rectangle to the specified point, effectively repositioning it within its superview.

func setFrameSize(NSSize)

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

var frameRotation: CGFloat

The angle of rotation, measured in degrees, applied to the view’s frame rectangle relative to its superview’s coordinate system.

Modifying the Bounds Rectangle

var bounds: NSRect

The view’s bounds rectangle, which expresses its location and size in its own coordinate system.

func setBoundsOrigin(NSPoint)

Sets the origin of the view’s bounds rectangle to a specified point.

func setBoundsSize(NSSize)

Sets the size of the view’s bounds rectangle to specified dimensions, inversely scaling its coordinate system relative to its frame rectangle.

var boundsRotation: CGFloat

The angle of rotation, measured in degrees, applied to the view’s bounds rectangle relative to its frame rectangle.

Managing the View’s Layer

var wantsLayer: Bool

A Boolean value indicating whether the view uses a layer as its backing store.

var wantsUpdateLayer: Bool

A Boolean value indicating which drawing path the view takes when updating its contents.

var layer: CALayer?

The Core Animation layer that the view uses as its backing store.

func makeBackingLayer()

Creates the view’s backing layer.

var layerContentsPlacement: NSViewLayerContentsPlacement

The current layer contents placement policy.

var layerContentsRedrawPolicy: NSViewLayerContentsRedrawPolicy

The contents redraw policy for the view’s layer.

var canDrawSubviewsIntoLayer: Bool

A Boolean value indicating whether the view incorporates content from its subviews into its own layer.

var layerUsesCoreImageFilters: Bool

A Boolean value indicating whether the view’s layer uses Core Image filters and needs in-process rendering.

Managing Layer-Related Properties

var alphaValue: CGFloat

The opacity of the view.

var frameCenterRotation: CGFloat

The rotation angle of the view around the center of its layer.

var backgroundFilters: [CIFilter]

An array of Core Image filters to apply to the view’s background.

var compositingFilter: CIFilter?

The Core Image filter used to composite the view’s contents with its background.

var contentFilters: [CIFilter]

An array of Core Image filters to apply to the contents of the view and its sublayers.

var shadow: NSShadow?

The shadow displayed underneath the view.

Drawing

func updateLayer()

Updates the view’s content by modifying its underlying layer.

func draw(NSRect)

Overridden by subclasses to draw the view’s image within the specified rectangle.

var canDraw: Bool

A Boolean value indicating whether drawing commands will produce any results.

var canDrawConcurrently: Bool

A Boolean value indicating whether the view can draw its contents on a background thread.

var visibleRect: NSRect

The portion of the view that is not clipped by its superviews.

func getRectsBeingDrawn(UnsafeMutablePointer<UnsafePointer<NSRect>?>?, count: UnsafeMutablePointer<Int>?)

Returns by indirection a list of nonoverlapping rectangles that define the area the view is being asked to draw in draw(_:).

func needsToDraw(NSRect)

Returns a Boolean value indicating whether the specified rectangle intersects any part of the area that the view is being asked to draw.

var wantsDefaultClipping: Bool

A Boolean value indicating whether AppKit’s default clipping behavior is in effect.

func bitmapImageRepForCachingDisplay(in: NSRect)

Returns a bitmap-representation object suitable for caching the specified portion of the view.

func cacheDisplay(in: NSRect, to: NSBitmapImageRep)

Draws the specified area of the view, and its descendants, into a provided bitmap-representation object.

Printing

func print(Any?)

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

func beginPage(in: NSRect, atPlacement: NSPoint)

Called at the beginning of each page, this method sets up the coordinate system so that a region inside the view’s bounds is translated to a specified location.

func dataWithEPS(inside: NSRect)

Returns EPS data that draws the region of the view within a specified rectangle.

func dataWithPDF(inside: NSRect)

Returns PDF data that draws the region of the view within a specified rectangle.

var printJobTitle: String

The view’s print job title.

var pageHeader: NSAttributedString

A default header string that includes the print job title and date.

var pageFooter: NSAttributedString

A default footer string that includes the current page number and page count.

func writeEPS(inside: NSRect, to: NSPasteboard)

Writes EPS data that draws the region of the view within a specified rectangle onto a pasteboard.

func writePDF(inside: NSRect, to: NSPasteboard)

Writes PDF data that draws the region of the view within a specified rectangle onto a pasteboard.

func drawPageBorder(with: NSSize)

Allows applications that use the AppKit pagination facility to draw additional marks on each logical page.

func drawSheetBorder(with: NSSize)

Allows applications that use the AppKit pagination facility to draw additional marks on each printed sheet.

Pagination

var heightAdjustLimit: CGFloat

The fraction 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.

var widthAdjustLimit: CGFloat

The fraction 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.

func adjustPageWidthNew(UnsafeMutablePointer<CGFloat>, left: CGFloat, right: CGFloat, limit: CGFloat)

Overridden by subclasses to adjust page width during automatic pagination.

func adjustPageHeightNew(UnsafeMutablePointer<CGFloat>, top: CGFloat, bottom: CGFloat, limit: CGFloat)

Overridden by subclasses to adjust page height during automatic pagination.

func knowsPageRange(NSRangePointer)

Returns true if the view handles page boundaries, false otherwise.

func rectForPage(Int)

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

func locationOfPrintRect(NSRect)

Invoked by print(_:) to determine the location of the region of the view being printed on the physical page.

Invalidating the View’s Content

func setNeedsDisplay(NSRect)

Marks the region of the view within the specified rectangle as needing display, increasing the view’s existing invalid region to include it.

var needsDisplay: Bool

A Boolean value that determines whether the view needs to be redrawn before being displayed.

func display()

Displays the view and all its subviews if possible, invoking each of the NSView methods lockFocus(), draw(_:), and unlockFocus() as necessary.

func display(NSRect)

Acts as display(), but confining drawing to a rectangular region of the view.

func displayIgnoringOpacity(NSRect)

Displays the view but confines drawing to a specified region and does not back up to the first opaque ancestor—it simply causes the view and its descendants to execute their drawing code.

func displayIgnoringOpacity(NSRect, in: NSGraphicsContext)

Causes the view and its descendants to be redrawn to the specified graphics context.

func displayIfNeeded()

Displays the view and all its subviews if any part of the view has been marked as needing display.

func displayIfNeeded(NSRect)

Acts as displayIfNeeded(), confining drawing to a specified region of the view.

func displayIfNeededIgnoringOpacity()

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

func displayIfNeededIgnoringOpacity(NSRect)

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

func translateRectsNeedingDisplay(in: NSRect, by: NSSize)

Translates the display rectangles by the specified delta.

var isOpaque: Bool

A Boolean value indicating whether the view fills its frame rectangle with opaque content.

func viewWillDraw()

Informs the view that it will be required to draw content.

Converting Coordinate Values

func backingAlignedRect(NSRect, options: AlignmentOptions = [])

Returns a backing store pixel-aligned rectangle in local view coordinates.

func convertFromBacking(NSPoint)

Converts a point from its pixel aligned backing store coordinate system to the view’s interior coordinate system.

func convertToBacking(NSPoint)

Converts a point from the view’s interior coordinate system to its pixel aligned backing store coordinate system.

func convertFromLayer(NSPoint)

Convert the point from the layer's interior coordinate system to the view’s interior coordinate system.

func convertToLayer(NSPoint)

Convert the size from the view’s interior coordinate system to the layer's interior coordinate system.

func convertFromBacking(NSRect)

Converts a rectangle from its pixel aligned backing store coordinate system to the view’s interior coordinate system.

func convertToBacking(NSRect)

Converts a rectangle from the view’s interior coordinate system to its pixel aligned backing store coordinate system.

func convertFromLayer(NSRect)

Convert the rectangle from the layer's interior coordinate system to the view’s interior coordinate system.

func convertToLayer(NSRect)

Convert the size from the view’s interior coordinate system to the layer's interior coordinate system.

func convertFromBacking(NSSize)

Converts a size from its pixel aligned backing store coordinate system to the view’s interior coordinate system.

func convertToBacking(NSSize)

Converts a size from the view’s interior coordinate system to its pixel aligned backing store coordinate system.

func convertFromLayer(NSSize)

Convert the size from the layer's interior coordinate system to the view’s interior coordinate system.

func convertToLayer(NSSize)

Convert the size from the view’s interior coordinate system to the layer's interior coordinate system.

func convert(NSPoint, from: NSView?)

Converts a point from the coordinate system of a given view to that of the view.

func convert(NSPoint, to: NSView?)

Converts a point from the view’s coordinate system to that of a given view.

func convert(NSSize, from: NSView?)

Converts a size from another view’s coordinate system to that of the view.

func convert(NSSize, to: NSView?)

Converts a size from the view’s coordinate system to that of another view.

func convert(NSRect, from: NSView?)

Converts a rectangle from the coordinate system of another view to that of the view.

func convert(NSRect, to: NSView?)

Converts a rectangle from the view’s coordinate system to that of another view.

func centerScanRect(NSRect)

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

Modifying the Coordinate System

func translateOrigin(to: NSPoint)

Translates the view’s coordinate system so that its origin moves to a new location.

func scaleUnitSquare(to: NSSize)

Scales the view’s coordinate system so that the unit square scales to the specified dimensions.

func rotate(byDegrees: CGFloat)

Rotates the view’s bounds rectangle by a specified degree value around the origin of the coordinate system, (0.0, 0.0).

Examining Coordinate System Modifications

var isFlipped: Bool

A Boolean value indicating whether the view uses a flipped coordinate system.

var isRotatedFromBase: Bool

A Boolean value indicating whether the view or any of its ancestors has ever had a rotation factor applied to its frame or bounds.

var isRotatedOrScaledFromBase: Bool

A Boolean value indicating whether the view or any of its ancestors has ever had a rotation factor applied to its frame or bounds, or has been scaled from the window’s base coordinate system.

Resizing Subviews

var autoresizesSubviews: Bool

A Boolean value indicating whether the view applies the autoresizing behavior to its subviews when its frame size changes.

var autoresizingMask: NSAutoresizingMaskOptions

The options that determine how the view is resized relative to its superview.

func resizeSubviews(withOldSize: NSSize)

Informs the view’s subviews that the view’s bounds rectangle size has changed.

func resize(withOldSuperviewSize: NSSize)

Informs the view that the bounds size of its superview has changed.

Creating Constraints Using Layout Anchors

var bottomAnchor: NSLayoutYAxisAnchor

A layout anchor representing the bottom edge of the view’s frame.

var centerXAnchor: NSLayoutXAxisAnchor

A layout anchor representing the horizontal center of the view’s frame.

var centerYAnchor: NSLayoutYAxisAnchor

A layout anchor representing the vertical center of the view’s frame.

var firstBaselineAnchor: NSLayoutYAxisAnchor

A layout anchor representing the baseline for the topmost line of text in the view.

var heightAnchor: NSLayoutDimension

A layout anchor representing the height of the view’s frame.

var lastBaselineAnchor: NSLayoutYAxisAnchor

A layout anchor representing the baseline for the bottommost line of text in the view.

var leadingAnchor: NSLayoutXAxisAnchor

A layout anchor representing the leading edge of the view’s frame.

var leftAnchor: NSLayoutXAxisAnchor

A layout anchor representing the left edge of the view’s frame.

var rightAnchor: NSLayoutXAxisAnchor

A layout anchor representing the right edge of the view’s frame.

var topAnchor: NSLayoutYAxisAnchor

A layout anchor representing the top edge of the view’s frame.

var trailingAnchor: NSLayoutXAxisAnchor

A layout anchor representing the trailing edge of the view’s frame.

var widthAnchor: NSLayoutDimension

A layout anchor representing the width of the view’s frame.

Managing the View’s Constraints

var constraints: [NSLayoutConstraint]

Returns the constraints held by the view.

func addConstraint(NSLayoutConstraint)

Adds a constraint on the layout of the receiving view or its subviews.

func addConstraints([NSLayoutConstraint])

Adds multiple constraints on the layout of the receiving view or its subviews.

func removeConstraint(NSLayoutConstraint)

Removes the specified constraint from the view.

func removeConstraints([NSLayoutConstraint])

Removes the specified constraints from the view.

Working with Layout Guides

func addLayoutGuide(NSLayoutGuide)

Adds the provided layout guide to the view.

var layoutGuides: [NSLayoutGuide]

The array of layout guide objects owned by this view.

func removeLayoutGuide(NSLayoutGuide)

Removes the provided layout guide from the view.

Measuring in Auto Layout

var fittingSize: NSSize

The minimum size of the view that satisfies the constraints it holds.

var intrinsicContentSize: NSSize

The natural size for the receiving view, considering only properties of the view itself.

func invalidateIntrinsicContentSize()

Invalidates the view’s intrinsic content size.

func contentCompressionResistancePriority(for: NSLayoutConstraintOrientation)

Returns the priority with which a view resists being made smaller than its intrinsic size.

func setContentCompressionResistancePriority(NSLayoutPriority, for: NSLayoutConstraintOrientation)

Sets the priority with which a view resists being made smaller than its intrinsic size.

func contentHuggingPriority(for: NSLayoutConstraintOrientation)

Returns the priority with which a view resists being made larger than its intrinsic size.

func setContentHuggingPriority(NSLayoutPriority, for: NSLayoutConstraintOrientation)

Sets the priority with which a view resists being made larger than its intrinsic size.

Aligning Views with Auto Layout

func alignmentRect(forFrame: NSRect)

Returns the view’s alignment rectangle for a given frame.

func frame(forAlignmentRect: NSRect)

Returns the view’s frame for a given alignment rectangle.

var alignmentRectInsets: EdgeInsets

The insets (in points) from the view’s frame that define its content rectangle.

var baselineOffsetFromBottom: CGFloat

The distance (in points) between the bottom of the view’s alignment rectangle and its baseline.

var firstBaselineOffsetFromTop: CGFloat

The distance (in points) between the top of the view’s alignment rectangle and its topmost baseline.

var lastBaselineOffsetFromBottom: CGFloat

The distance (in points) between the bottom of the view’s alignment rectangle and its bottommost baseline.

Triggering Auto Layout

var needsLayout: Bool

A Boolean value indicating whether the view needs a layout pass before it can be drawn.

func layout()

Perform layout in concert with the constraint-based layout system.

func layoutSubtreeIfNeeded()

Updates the layout of the receiving view and its subviews based on the current views and constraints.

var needsUpdateConstraints: Bool

A Boolean value indicating whether the view’s constraints need to be updated.

func updateConstraints()

Update constraints for the view.

func updateConstraintsForSubtreeIfNeeded()

Updates the constraints for the receiving view and its subviews.

Opting In to Auto Layout

class func requiresConstraintBasedLayout()

Returns a Boolean value indicating whether the view depends on the constraint-based layout system.

var translatesAutoresizingMaskIntoConstraints: Bool

A Boolean value indicating whether the view’s autoresizing mask is translated into constraints for the constraint-based layout system.

Debugging Auto Layout

See Auto Layout Guide for more details on debugging constraint-based layout.

func constraintsAffectingLayout(for: NSLayoutConstraintOrientation)

Returns the constraints impacting the layout of the view for a given orientation.

var hasAmbiguousLayout: Bool

A Boolean value indicating whether the constraints impacting the layout of the view incompletely specify the location of the view.

func exerciseAmbiguityInLayout()

Randomly changes the frame of a view with an ambiguous layout between the different valid values.

Focusing

func lockFocus()

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

func lockFocusIfCanDraw()

Locks the focus to the view atomically if the canDraw method returns true and returns the value of canDraw.

func lockFocusIfCanDraw(in: NSGraphicsContext)

Locks the focus to the view atomically if drawing can occur in the specified graphics context.

func unlockFocus()

Unlocks focus from the current view.

class func focusView()

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

Focus Ring Drawing

var focusRingType: NSFocusRingType

The type of focus ring drawn around the view.

var focusRingMaskBounds: NSRect

The focus ring mask bounds, specified in the view’s coordinate space.

func drawFocusRingMask()

Draws the focus ring mask for the view.

func noteFocusRingMaskChanged()

Invoked to notify the view that the focus ring mask requires updating.

func setKeyboardFocusRingNeedsDisplay(NSRect)

Invalidates the area around the focus ring.

class func defaultFocusRingType()

Returns the default focus ring type.

Getting the Vibrancy Setting

var allowsVibrancy: Bool

A Boolean value indicating whether the view ensures it is vibrant on top of other content.

Fullscreen Mode

func exitFullScreenMode(options: [String : Any]? = nil)

Instructs the view to exit full screen mode.

var isInFullScreenMode: Bool

A Boolean value indicating whether the view is in full screen mode.

Hiding Views

var isHidden: Bool

A Boolean value indicating whether the view is hidden.

var isHiddenOrHasHiddenAncestor: Bool

A Boolean value indicating whether the view is hidden from sight because it, or one of its ancestors, is marked as hidden.

func viewDidHide()

Invoked when the view is hidden, either directly, or in response to an ancestor being hidden.

func viewDidUnhide()

Invoked when the view is unhidden, either directly, or in response to an ancestor being unhidden

Managing Live Resize

var inLiveResize: Bool

A Boolean value indicating whether the view is being rendered as part of a live resizing operation.

var preservesContentDuringLiveResize: Bool

A Boolean value indicating whether the view optimizes live-resize operations by preserving content that has not moved.

func getRectsExposedDuringLiveResize(UnsafeMutablePointer<NSRect>!, count: UnsafeMutablePointer<Int>)

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

var rectPreservedDuringLiveResize: NSRect

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

func viewWillStartLiveResize()

Informs the view of the start of a live resize—the user has started resizing the view.

func viewDidEndLiveResize()

Informs the view of the end of a live resize—the user has finished resizing the view.

Managing Gesture Recognizers

var gestureRecognizers: [NSGestureRecognizer]

The gesture recognize objects currently attached to the view.

func addGestureRecognizer(NSGestureRecognizer)

Attaches a gesture recognizer to the view.

func removeGestureRecognizer(NSGestureRecognizer)

Detaches a gesture recognizer from the view.

Event Handling

func acceptsFirstMouse(for: NSEvent?)

Overridden by subclasses to return true if the view should be sent a mouseDown(with:) message for an initial mouse-down event, false if not.

func hitTest(NSPoint)

Returns the farthest descendant of the view in the view hierarchy (including itself) that contains a specified point, or nil if that point lies completely outside the view.

func mouse(NSPoint, in: NSRect)

Returns whether a region of the view contains a specified point, accounting for whether the view is flipped or not.

func performKeyEquivalent(with: NSEvent)

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

var mouseDownCanMoveWindow: Bool

A Boolean value indicating whether the view can pass mouse down events through to its superviews.

var inputContext: NSTextInputContext?

The text input context object for the view.

Touch Event Handling

var acceptsTouchEvents: Bool

A Boolean value indicating whether the view accepts touch events.

var wantsRestingTouches: Bool

A Boolean value indicating whether the view wants resting touches.

Key-view Loop Management

var canBecomeKeyView: Bool

A Boolean value indicating whether the view can become key view.

var needsPanelToBecomeKey: Bool

A Boolean value indicating whether the view needs its panel to become the key window before it can handle keyboard input and navigation.

var nextKeyView: NSView?

The view object that follows the current view in the key view loop.

var nextValidKeyView: NSView?

The closest view object in the key view loop that follows the current view in the key view loop and accepts first responder status.

var previousKeyView: NSView?

The view object preceding the current view in the key view loop.

var previousValidKeyView: NSView?

The closest view object in the key view loop that precedes the current view and accepts first responder status.

Scrolling

class func isCompatibleWithResponsiveScrolling()

Returns a Boolean value indicating whether the view supports responsive scrolling.

func prepareContent(in: NSRect)

Prepares the overdraw region for drawing.

var preparedContentRect: NSRect

The portion of the view that has been rendered and is available for responsive scrolling.

func scroll(NSPoint)

Scrolls the view’s closest ancestor NSClipView object so a point in the view lies at the origin of the clip view's bounds rectangle.

func scrollToVisible(NSRect)

Scrolls the view’s closest ancestor NSClipView object the minimum distance needed so a specified region of the view becomes visible in the clip view.

func autoscroll(with: NSEvent)

Scrolls the view’s closest ancestor NSClipView object proportionally to the distance of an event that occurs outside of it.

func adjustScroll(NSRect)

Overridden by subclasses to modify a given rectangle, returning the altered rectangle.

func scroll(NSRect, by: NSSize)

Copies the visible portion of the view’s rendered image within a region and lays that portion down again at a specified offset .

var enclosingScrollView: NSScrollView?

The nearest ancestor scroll view that contains the current view.

func scroll(NSClipView, to: NSPoint)

Notifies the superview of a clip view that the clip view needs to reset the origin of its bounds rectangle.

func reflectScrolledClipView(NSClipView)

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

Dragging Operations

func register(forDraggedTypes: [String])

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

func unregisterDraggedTypes()

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

var registeredDraggedTypes: [String]

The array of pasteboard drag types that the view can accept.

func dragFile(String, from: NSRect, slideBack: Bool, event: NSEvent)

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

func dragPromisedFiles(ofTypes: [String], from: NSRect, source: Any, slideBack: Bool, event: NSEvent)

Initiates a dragging operation from the view, 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.

func shouldDelayWindowOrdering(for: NSEvent)

Allows the user to drag objects from the view without activating the app or moving the window of the view forward, possibly obscuring the destination.

Handling Smart Magnification

func rectForSmartMagnification(at: NSPoint, in: NSRect)

Returns the appropriate rectangle to use when magnifying around the specified point.

Controlling Notifications

var postsFrameChangedNotifications: Bool

A Boolean value indicating whether the view posts notifications when its frame rectangle changes.

var postsBoundsChangedNotifications: Bool

A Boolean value indicating whether the view posts notifications when its bounds rectangle changes.

Responding to Changes in Backing Store Properties

func viewDidChangeBackingProperties()

Responds when the view’s backing store properties change.

Searching by Tag

func viewWithTag(Int)

Returns the view’s nearest descendant (including itself) with a specific tag, or nil if no subview has that tag.

var tag: Int

The view’s tag, which is an integer that you use to identify the view within your app.

Tooltips

func addToolTip(NSRect, owner: Any, userData: UnsafeMutableRawPointer?)

Creates a tooltip for a defined area the view and returns a tag that identifies the tooltip rectangle.

func removeAllToolTips()

Removes all tooltips assigned to the view.

func removeToolTip(NSToolTipTag)

Removes the tooltip identified by specified tag.

var toolTip: String?

The text for the view’s tooltip.

Managing Tracking Rectangles

func addTrackingRect(NSRect, owner: Any, userData: UnsafeMutableRawPointer?, assumeInside: Bool)

Establishes an area for tracking mouse-entered and mouse-exited events within the view and returns a tag that identifies the tracking rectangle.

func removeTrackingRect(NSTrackingRectTag)

Removes the tracking rectangle identified by a tag.

Managing Tracking Areas

func addTrackingArea(NSTrackingArea)

Adds a given tracking area to the view.

func removeTrackingArea(NSTrackingArea)

Removes a given tracking area from the view.

var trackingAreas: [NSTrackingArea]

An array of the view’s tracking areas.

func updateTrackingAreas()

Invoked automatically when the view’s geometry changes such that its tracking areas need to be recalculated.

Managing Cursor Tracking

func addCursorRect(NSRect, cursor: NSCursor)

Establishes the cursor to be used when the mouse pointer lies within a specified region.

func removeCursorRect(NSRect, cursor: NSCursor)

Completely removes a cursor rectangle from the view.

func discardCursorRects()

Invalidates all cursor rectangles set up using addCursorRect(_:cursor:).

func resetCursorRects()

Overridden by subclasses to define their default cursor rectangles.

Managing Contextual Menus

func menu(for: NSEvent)

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

class func defaultMenu()

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

func willOpenMenu(NSMenu, with: NSEvent)

Called just before a contextual menu for a view is opened on screen.

func didCloseMenu(NSMenu, with: NSEvent?)

Called after a contextual menu that was displayed from the receiving view has been closed.

Writing Conforming Rendering Instructions

func beginDocument()

Invoked at the beginning of the printing session, this method sets up the current graphics context.

func endDocument()

This method is invoked at the end of the printing session.

func endPage()

Writes the end of a conforming page.

Displaying Definition Windows

func showDefinition(for: NSAttributedString?, at: NSPoint)

Shows a window displaying the definition of the attributed string at the specified point.

Drawing Find Indicator

var isDrawingFindIndicator: Bool

A Boolean value indicating whether the view or one of its ancestors is being drawn for a find indicator.

Managing the Content Layout Direction

var userInterfaceLayoutDirection: NSUserInterfaceLayoutDirection

The layout direction for content in the view.

Specifying the OpenGL Surface Resolution

var wantsBestResolutionOpenGLSurface: Bool

A Boolean value indicating whether the view wants an OpenGL backing surface with a resolution greater than 1 pixel per point.

Configuring Pressure

var pressureConfiguration: NSPressureConfiguration?

Configures the behavior and progression of the Force Touch trackpad when responding to touch input produced by the user when the cursor is over the view.

Deprecated Methods

func shouldDrawColor()

Returns a Boolean value indicating whether the view is being drawn to an environment that supports color.

Deprecated
func allocateGState()

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

Deprecated
func gState()

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

Deprecated
func setUpGState()

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

Deprecated
func renewGState()

Invalidates the view’s graphics state object, if it has one.

Deprecated
func releaseGState()

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

Deprecated

Constants

NSBorderType

These constants specify the type of a view’s border.

NSAutoresizingMaskOptions

Constants used by the autoresizingMask property.

NSToolTipTag

This type describes the rectangle used to identify a tooltip rectangle.

NSTrackingRectTag

This type describes the rectangle used to track the mouse.

Full Screen Mode Options

These constants are keys that you can use in the options dictionary in enterFullScreenMode(_:withOptions:) and exitFullScreenMode(options:).

NSViewLayerContentsRedrawPolicy

Constants that specify how layer resizing is handled when a view is layer-backed or layer-hosting. For more information, see the layerContentsRedrawPolicy property.

NSViewLayerContentsPlacement

These constants specify the location of the layer content when the content is not re-rendered in response to view resizing. For more information, see the layerContentsPlacement property.

NSDefinition Presentation Constants

These constants are used to control how definition windows are displayed by showDefinition(for:range:options:baselineOriginProvider:). If this option is unspecified, the definition will be shown in either of those presentation forms depending on the 'Contextual Menu:' setting in Dictionary application preferences.

Notifications

static let NSViewBoundsDidChange: NSNotification.Name

Posted whenever the NSView’s bounds rectangle changes to a new value independently of the frame rectangle, but only when the view’s postsBoundsChangedNotifications property is true.

static let NSViewFocusDidChange: NSNotification.Name

Deprecated in macOS 10.4 and later. Posted for an NSView object and each of its descendants (recursively) whenever the frame or bounds geometry of the view changed.

static let NSViewFrameDidChange: NSNotification.Name

Posted whenever the view’s frame rectangle changes to a new value, but only when the view’s postsFrameChangedNotifications property is true.

static let NSViewDidUpdateTrackingAreas: NSNotification.Name

Posted whenever an NSView object recalculates its tracking areas.

static let NSViewGlobalFrameDidChange: NSNotification.Name

Posted whenever an NSView object that has attached surfaces (that is, NSOpenGLContext objects) moves to a different screen, or other cases where the NSOpenGLContext object needs to be updated.

Instance Methods

func rulerView(NSRulerView, didAdd: NSRulerMarker)

Informs the client that aRulerView allowed the user to add aMarker.

func rulerView(NSRulerView, didMove: NSRulerMarker)

Informs the client that aRulerView allowed the user to move aMarker.

func rulerView(NSRulerView, didRemove: NSRulerMarker)

Informs the client that aRulerView allowed the user to remove aMarker.

func rulerView(NSRulerView, handleMouseDownWith: NSEvent)

Informs the client that the user has pressed the mouse button while the cursor is in the ruler area of aRulerView.

func rulerView(NSRulerView, locationFor: NSPoint)func rulerView(NSRulerView, pointForLocation: CGFloat)
func rulerView(NSRulerView, shouldAdd: NSRulerMarker)

Requests permission for aRulerView to add aMarker, an NSRulerMarker being dragged onto the ruler by the user.

func rulerView(NSRulerView, shouldMove: NSRulerMarker)

Requests permission for aRulerView to move aMarker.

func rulerView(NSRulerView, shouldRemove: NSRulerMarker)

Requests permission for aRulerView to remove aMarker.

func rulerView(NSRulerView, willAdd: NSRulerMarker, atLocation: CGFloat)

Informs the client that aRulerView will add the new NSRulerMarker, aMarker.

func rulerView(NSRulerView, willMove: NSRulerMarker, toLocation: CGFloat)

Informs the client that aRulerView will move aMarker, an NSRulerMarker already on the ruler view.

func rulerView(NSRulerView, willSetClientView: NSView)

Informs the client view that aRulerView is about to be appropriated by newClient.