NSTextView
A view that draws text and handles user interactions with that text.
Declaration
class NSTextViewMentioned in
Overview
The NSTextView class is the front-end class to the AppKit text system. The class draws the text managed by the back-end components and handles user events to select and modify its text, in addition to supporting rich text, attachments, input management, and key binding, and marked text attributes.
NSTextView is the principal means to obtain a text object that caters to almost all needs for displaying and managing text at the user interface level. While NSTextView is a subclass of the NSText class — which declares the most general Cocoa interface to the text system — NSTextView adds major features beyond the capabilities of NSText. You can also do more powerful and more creative text manipulation (such as displaying text in a circle) using NSTextStorage, NSTextLayoutManager, NSTextContainer, and related classes.
You’re more likely to use the NSTextView class than NSText. It’s also important to remember that NSTextView conforms to a large number of protocols, the methods of which are available to instances of the NSTextView class.
NSTextView communicates with its delegate through methods declared both by the NSTextViewDelegate and by its superclass’s protocol, NSTextDelegate. All delegation messages come from the first text view.
In macOS 12 and later, if you explicitly call the layoutManager property on a text view or text container, the framework reverts to a compatibility mode that uses NSLayoutManager. The text view also switches to this compatibility mode when it encounters text content that’s not yet supported, such as NSTextTable.
About Delegate Methods
The NSTextView class communicates with its delegate through methods declared both by the NSTextViewDelegate and by its superclass’s protocol, NSTextDelegate. All delegation messages come from the first text view.
Becoming the first responder
When the system invokes becomeFirstResponder() on a text view, if the previous first responder was not a text view on the same layout manager as the receiving text view, the receiving text view draws the selection and updates the insertion point if necessary.
To make a text view the first responder, call the containing window’s makeFirstResponder(_:) method. Never invoke a text view’s becomeFirstResponder() method directly.
Resigning as first responder
When the system invokes resignFirstResponder() on a text view, if the object that will become the new first responder is a text view attached to the same layout manager as the receiver, the receiving text view returns true with no further action. Otherwise, it sends a textShouldEndEditing(_:) message to its delegate (if any). If the delegate returns false, the text view returns false. If the delegate returns true, the text view hides the selection highlighting and posts an didEndEditingNotification to the default notification center and then returns true.
Topics
Creating a text view
Managing the text view’s content
Registering services information
Accessing text system objects
stronglyReferencesTextStoragefieldEditor()textContainerreplaceTextContainer(_:)textContainerInsettextContainerOrigininvalidateTextContainerOrigin()textLayoutManagerlayoutManagertextContentStoragetextStorage
Setting graphics attributes
Controlling text display
setNeedsDisplay(_:avoidAdditionalLayout:)shouldDrawInsertionPointdrawInsertionPoint(in:color:turnedOn:)drawBackground(in:)setConstrainedFrameSize(_:)cleanUpAfterDragOperation()showFindIndicator(for:)scrollableDocumentContentTextView()scrollablePlainDocumentContentTextView()scrollableTextView()
Inserting text
Setting behavioral attributes
allowsUndoisEditableisSelectableisFieldEditorisRichTextimportsGraphicssetBaseWritingDirection(_:range:)defaultParagraphStyleoutline(_:)allowsImageEditingisAutomaticQuoteSubstitutionEnabledtoggleAutomaticQuoteSubstitution(_:)isAutomaticLinkDetectionEnabledtoggleAutomaticLinkDetection(_:)displaysLinkToolTipsisAutomaticTextCompletionEnabledtoggleAutomaticTextCompletion(_:)usesAdaptiveColorMappingForDarkAppearanceusesRolloverButtonForSelection
Using text formatting controls
Managing the selection
selectedRangessetSelectedRange(_:)setSelectedRange(_:affinity:stillSelecting:)setSelectedRanges(_:affinity:stillSelecting:)selectionAffinityselectionGranularityinsertionPointColorupdateInsertionPointStateAndRestartTimer(_:)selectedTextAttributesmarkedTextAttributeslinkTextAttributescharacterIndexForInsertion(at:)updateCandidates()
Managing the pasteboard
preferredPasteboardType(from:restrictedToTypesFrom:)readSelection(from:)readSelection(from:type:)readablePasteboardTypeswritablePasteboardTypeswriteSelection(to:type:)writeSelection(to:types:)validRequestor(forSendType:returnType:)
Setting text attributes
alignJustified(_:)changeAttributes(_:)changeColor(_:)setAlignment(_:range:)typingAttributesuseStandardKerning(_:)lowerBaseline(_:)raiseBaseline(_:)turnOffKerning(_:)loosenKerning(_:)tightenKerning(_:)useStandardLigatures(_:)turnOffLigatures(_:)useAllLigatures(_:)toggleTraditionalCharacterShape(_:)
Clicking and pasting
Supporting undo
Customizing subclass behaviors
updateFontPanel()updateRuler()acceptableDragTypesupdateDragTypeRegistration()selectionRange(forProposedRange:granularity:)rangeForUserCharacterAttributeChangerangesForUserCharacterAttributeChangerangeForUserParagraphAttributeChangerangesForUserParagraphAttributeChangerangeForUserTextChangerangesForUserTextChangeshouldChangeText(in:replacementString:)shouldChangeText(inRanges:replacementStrings:)didChangeText()smartInsertDeleteEnabledsmartDeleteRange(forProposedRange:)smartInsert(afterStringFor:replacing:)smartInsert(beforeStringFor:replacing:)smartInsert(for:replacing:before:after:)toggleSmartInsertDelete(_:)
Working with the spelling checker
isContinuousSpellCheckingEnabledspellCheckerDocumentTagtoggleContinuousSpellChecking(_:)isGrammarCheckingEnabledtoggleGrammarChecking(_:)setSpellingState(_:range:)
Working with the sharing service picker
Supporting the ruler view
rulerView(_:didMove:)rulerView(_:willMove:toLocation:)rulerView(_:shouldMove:)rulerView(_:didRemove:)rulerView(_:shouldRemove:)rulerView(_:didAdd:)rulerView(_:shouldAdd:)rulerView(_:willAdd:atLocation:)rulerView(_:handleMouseDownWith:)
Dragging
dragImageForSelection(with:origin:)dragOperation(for:type:)dragSelection(with:offset:slideBack:)acceptsGlyphInfo
Speaking text
Working with panels
usesFontPanelusesFindPanelperformFindPanelAction(_:)orderFrontLinkPanel(_:)orderFrontListPanel(_:)orderFrontSpacingPanel(_:)orderFrontTablePanel(_:)orderFrontSubstitutionsPanel(_:)
Performing text completion
complete(_:)completions(forPartialWordRange:indexOfSelectedItem:)insertCompletion(_:forPartialWordRange:movement:isFinal:)rangeForUserCompletion
Checking and substituting text
checkTextInDocument(_:)checkTextInSelection(_:)checkText(in:types:options:)handleTextCheckingResults(_:forRange:types:options:orthography:wordCount:)enabledTextCheckingTypesisAutomaticDashSubstitutionEnabledtoggleAutomaticDashSubstitution(_:)isAutomaticDataDetectionEnabledtoggleAutomaticDataDetection(_:)isAutomaticSpellingCorrectionEnabledtoggleAutomaticSpellingCorrection(_:)isAutomaticTextReplacementEnabledtoggleAutomaticTextReplacement(_:)performValidatedReplacement(in:with:)
Getting the writing tools status
Supporting QuickLook
Changing layout orientation
Using the Find Bar
Constants
NSSelectionGranularityNSSelectionAffinityNSFindPanelActionInput Sources Locale IdentifiersFind Panel Search MetadataNSFindPanelSubstringMatchType
Notifications
didChangeSelectionNotificationwillChangeNotifyingTextViewNotificationdidChangeTypingAttributesNotificationdidSwitchToNSLayoutManagerNotificationwillSwitchToNSLayoutManagerNotification
Interacting with the Touch Bar
allowsCharacterPickerTouchBarItemcandidateListTouchBarItemupdateTextTouchBarItems()updateTouchBarItemIdentifiers()
Instance Properties
allowedWritingToolsResultOptionsinlinePredictionTypemathExpressionCompletionTypetextHighlightAttributeswritingToolsBehavior