Manage text storage and perform custom layout of text-based content in your app's views using TextKit.

Posts under TextKit tag

50 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

TextKit 2 calls NSTextLayoutFragment's draw method too often
The following is verbatim of a feedback report (FB19809442) I submitted, shared here as someone else might be interested to see it (I hate the fact that we can't see each other's feedbacks). On iOS 16, TextKit 2 calls NSTextLayoutFragment's draw(at:in:) method once for the first paragraph, but for every other paragraph, it calls it continuously on every scroll step in the UITextView. (The first paragraph is not cached; its draw is called again when it is about to be displayed again, but then it is again called only once per its lifecycle.) On iOS 17, the behavior is similar; the draw method gets called once for the 1st and 2nd paragraph, and for every other paragraph it again gets called continuously as a user scrolls a UITextView. On iOS 18 (and iOS 26 beta 4), TextKit 2 calls the layout fragment's draw(at:in:) on every scroll step in the UITextView, for all paragraphs. This results in terrible performance. TextKit 2 is promised to bring many performance benefits by utilizing the viewport - a new concept that represents the visible area of a text view, along with a small overscroll. However, having the draw method being constantly called almost negates all the performance benefits that viewport brings. Imagine what could happen if someone needs to add just a bit of logic to that draw method. FPS drops significantly and UX is terribly degraded. I tried optimizing this by only rendering those text line fragments which are in the viewport, by using NSTextViewportLayoutController.viewportBounds and converting NSTextLineFragment.typographicBounds to the viewport-relative coordinate space (i.e. the coordinate space of the UITextView itself). However, this patch only works on iOS 18 where the draw method is called too many times, as the viewport changes. (I may have some other problems in my implementation, but I gave up on improving those, as this can't work reliably on all OS versions since the underlying framework isn't calling the method consistently.) Is this expected? What are our options for improving performance in these areas?
6
0
143
1w
TextKit 2 undocumented and unexpected behavior in textViewportLayoutControllerDidLayout
The NSTextViewportLayoutControllerDelegate.textViewportLayoutControllerDidLayout(_:) documentation states that Layout information on textViewportLayoutController is up-to-date at the point of this call. however it is easy to put the NSTextViewportLayoutController in a state where after calling textViewportLayoutControllerDidLayout, the value of viewportRange is nil (unexpected) and value of the property viewportBounds is .zero The TextKit2 sample application found at https://developer.apple.com/documentation/uikit/using-textkit-2-to-interact-with-text makes that assumption as well, and in few places force unwrap the value of viewportRange, that leads to runtime crashes. This behavior is also discussed in Developer Forum thread about TextKit2 viewport relocation: https://developer.apple.com/forums/thread/761364?answerId=800516022#800516022 How to reproduce: Run Mac target of LayoutWithTextKit2 sample project found at https://developer.apple.com/documentation/uikit/using-textkit-2-to-interact-with-text locate menu.rtf file and duplicate its content several times - the goal is to increase the length of the layout text quickly resize application window - that results in viewport layouts - that result in out-of-bound viewport - that results ina crash OR quickly scroll down/up to the end of the document using scroller bar on the right side of the window Reproducible 100% The situation occurs when the document is not fully laid out, the estimated size (height) of the content exceeds the final (correct) height, and the layoutViewport() function is executed quickly. Resulting in partial viewport layout, and once the viewport moves outside of the document's total height, the viewportLayoutController starts to report viewportRange = nil. FB19698121 Why does it happen? Is it expected? How to recover from that state? And most importantly, how to make the NSTextLayoutManager display the portion of the document that is currently scrolled to. and how to do it without for ce layout the full document on each viewportLayout()
1
0
108
2w
[TextKit2] - Wrong document height sometimes ?
Hello 👋 I'm playing with the Apple TextKit2 sample app (particularly on macOS). I found that on some long document the evaluated height given by enumerateTextLayoutFragments API is wrong (or at least not I expect) which imply I can no longer scroll in my document even if I have not reached the end of it (which is not what I expect as you can guess). I'm clearly missing a point here. I can reproduce it on the Apple sample app by only changing the text content: https://developer.apple.com/documentation/UIKit/using-textkit-2-to-interact-with-text Using TextKit2, is it my responsability as developer to check that I've reached end of the scrollview whether not being at the end location of the document and call some specific TextKit2 API to invalidate estimation or something ? Here is an updated version of the Apple sample app with another text content that show the issue. https://drive.google.com/file/d/1jtTD84oqGAG4_A9DfqFl_yHmbLKhF1e8/view?usp=sharing Environment: Xcode 16.4 - macOS 15.6 If someone could help me with this, I would be extremely grateful. It puzzles me. NB: I've observed that resizing the window a bit seems to force a new layout and make TextKit2 returns a more accurate height, ... until you reach the end of the document.
3
0
71
Aug ’25
Best Option for Programmatically Scrolling Long Dynamic Text
Hello! I am trying to create an iOS app that is based around a very large, vertically scrolling text view. The text is broken up into many sections, and the user should be able to press buttons in the navigation, which programmatically scroll to those sections. The user can also change the font size in a settings menu. It should generally keep the user's spot when resizing fonts or rotating the screen (from portrait to landscape). The problem I've been having is that no method of lazy text loading allows accurate enough navigation, and the text is too long to calculate the whole UI all at once. Here's my process in trying to find a solution: My app is built in SwiftUI, so I started with a ScrollView and a LazyVStack, and I used .scrollPosition() and bound it to an Int?. It worked pretty well for most scroll locations both on screen and far off the screen, but when I programmatically scroll to a location that is off the screen but not very far off, it completely misses. So, I investigated UIKit, and found that UITextView was a much better fit for the way I wanted to present the long text. I could also programmatically navigate by storing the NSRange of each section. I tried to use scrollRangeToVisible(), but for long distance it would scroll so that the desired section was just below the viewport and thus off screen. Then I tried to use UITextView's textLayoutManager.textViewportLayoutController.relocateViewport() to send it to the correct NSTextRange, it would not jump all the way, but instead would do nothing until I tried to scroll again and it would jump slightly forward. I tried to use textViewportLayoutController.layoutViewport() after the jump, and that fixed the glitch when scrolling, but it still did not jump to the correct place, only slightly forward. Then, I looked into TextKit 2 and the way it worked to try to find a solution. From what I can tell, it seems that to affect the NSTextViewportLayoutController without having to rewrite it, I need an NSTextViewportLayoutControllerDelegate, but the delegate required me to manually lay out the views, and in all the examples I've seen that use a custom NSTextViewportLayoutControllerDelegate, they wrote their own custom text view instead of using the default UITextView. I started looking into writing a custom text view so I can get the programmatic scroll to work consistently. However, it felt like, from a maintainability standpoint, it would probably be best to stick with what Apple has already implemented. For now, I found a workaround that scrolls consistently. Here is the code: if let start = self.textView.position(from: self.textView.beginningOfDocument, offset: desiredLineRange.location) { let location = textView.caretRect(for: start) self.textView.setContentOffset(CGPoint(x: 0, y: location.origin.y), animated: false) } if let start = self.textView.position(from: self.textView.beginningOfDocument, offset: desiredLineRange.location) { let location = textView.caretRect(for: start) self.textView.setContentOffset(CGPoint(x: 0, y: location.origin.y), animated: false) } It does the job, because the first time it gets close enough, and the second time it gets to the precise location, but it just feels like a bit of a hack to run the same code twice. I was wondering if anyone knows what I could be doing wrong and if Apple provides any solutions for this? (Also, all my UIKit navigation attempts ran inside an @objc func, which I passed using button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside). Just so you know in case it may be a problem with the way Swift and UIKit handle concurrency/parallel tasks). Thank you!
0
0
148
Jul ’25
Cursor position sync between IOS touch screen and app textview.
The app puts button values into a text view area and controls the cursor. Upon an IOS touch screen, cut or paste, the IOS cursor loses sync with the app cursor causing an address out of bounds and fails. The IOS cut or paste changes the cursor position and the text.endIndex address by shrinking or expanding the text field. IOS doesn't know about the app cursorPosition. If IOS could update the app cursor position and the text.endIndex position would solve the problem. Or if the app knew about the IOS change could update the app cursor position and the text.endIndex. The current work around is the user sets the cursor to the text.startIndex using an app navigating button before the touch screen. The app does not fail. The user then navigates the cursor using arrow buttons to another position. To see this happen download the free SummaGramIPAD Trial.(13") TSIs have been requested with engineer suggestions for well over one year. I hope someone could figure this out. I just finished SummaGram iPhone and would like to host it. Thanks for your help. Charlie
0
0
42
Jul ’25
RichText(markdown) live editor using TextEditor
hi everyone, any thought on how to implement a RichText(markdown) live editor using the new TextEditor(text: AttributedString, selection: AttributedTextSelection)? Having issues like: how to get the location of the selected text relatived to the TextEditor bounds, which is used to show and position a floating toolbar. how to detect the cursor point is a new line and the content is "# ", (of couse now the user enter a space after the "#"), and if so, how to apply a H1 heading format to that line much more issues like this, but these two are how to get me started, thanks struct TextEditor8: View { @State var text: AttributedString @State var selection = AttributedTextSelection() @State var isShowFloatingToolbar = false @State var toolbarPosition: CGPoint = .zero init() { var text = AttributedString("Hello ✋🏻,Who is ready for Cooking?") let range = text.characters.indices(where: \.isUppercase) text[range].foregroundColor = .blue _text = State(initialValue: text) } var body: some View { ZStack(alignment: .topLeading) { GeometryReader { geo in TextEditor(text: $text, selection: $selection) .onChange(of: selection, perform: { newV in let v = text[newV] if v.characters.isEmpty { isShowFloatingToolbar = false } else { isShowFloatingToolbar = true toolbarPosition = CGPoint(x: 20, y: 20) // how to get CGPoint relatived to TextEditor from selection } print("vvvv", v.characters.isEmpty) }) } if isShowFloatingToolbar { FloatingToolbarAtSelection() .position(toolbarPosition) } } } }
1
0
94
Jun ’25
Text in NSTextView with TextKit2 is cropped instead of being soft-wrapped
I noticed that sometimes TextKit2 decides to crop some text instead of soft-wrapping it to the next line. This can be reproduced by running the code below, then resizing the window by dragging the right margin to the right until you see the text with green background (starting with “file0”) at the end of the first line. If you now slowly move the window margin back to the left, you’ll see that for some time that green “file0” text is cropped and so is the end of the text with red background, until at some point it is soft-wrapped on the second line. I just created FB18289242. Is there a workaround? class ViewController: NSViewController { override func loadView() { let textView = NSTextView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) let string = NSMutableAttributedString(string: "file0\t143548282\t1970-01-01T00:00:00Z\t1\t1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75", attributes: [.foregroundColor: NSColor.labelColor, .backgroundColor: NSColor.red.withAlphaComponent(0.2)]) string.append(NSAttributedString(string: "file0\t143548290\t1970-01-01T00:05:00Z\t 2\t0f6460d0ed7825fed6bda0f4d9c14942d88edc7ff236479212e69f081815e6f1742c272753b77cc6437f06ef93a46271c6ff9513c68945075212434080e60c82", attributes: [.foregroundColor: NSColor.labelColor, .backgroundColor: NSColor.green.withAlphaComponent(0.2)])) textView.textContentStorage!.textStorage!.setAttributedString(string) textView.autoresizingMask = [.width, .height] let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) scrollView.documentView = textView scrollView.hasVerticalScroller = true scrollView.translatesAutoresizingMaskIntoConstraints = false view = scrollView } }
0
0
72
Jun ’25
How to replace layoutManager with textLayoutManager for a flexible dynamic height UITextView
In order to create a UITextView like that of the Messages app whose height grows to fits its contents (number of lines), I subclassed UITextView and customized the intrinsicContentSize like so: override var intrinsicContentSize: CGSize { var size = super.intrinsicContentSize if size.height == UIView.noIntrinsicMetric { layoutManager.glyphRange(for: textContainer) size.height = layoutManager.usedRect(for: textContainer).height + textContainerInset.top + textContainerInset.bottom } return size } As noted at WWDC, accessing layoutManager will force TextKit 1, we should instead use textLayoutManager. How can this code be migrated to support TextKit 2?
3
0
116
Jun ’25
NSTextLists not rendered when NSTextContentStorageDelegate textContentStorage (_:, textParagraphWith:) is implemented
I have a UITextView that contains paragraphs with text bullet lists (via NSTextList). I also implement NSTextContentStorageDelegate.textContentStorage(_:, textParagraphWith:) in order to apply some custom attributes to the text without affecting the underlying attributed text. My implementation returns a new NSParagraph that modifies the foreground color of the text. I based this on the example in the WWDC 21 session "Meet Text Kit 2". UITextView stops rendering the bullets when I implement the delegate function and return a custom paragraph. Why? func textContentStorage(_ textContentStorage: NSTextContentStorage, textParagraphWith range: NSRange) -> NSTextParagraph? { guard let originalText = textContentStorage.textStorage?.attributedSubstring(from: range) else { return nil } let updatedText = NSMutableAttributedString(attributedString: originalText) updatedText.addAttribute(.foregroundColor, value: UIColor.green, range: NSRange(location: 0, length: updatedText.length)) let paragraph = NSTextParagraph(attributedString: updatedText) // Verify that the text still contains NSTextList if let paragraphStyle = paragraph.attributedString.attribute(.paragraphStyle, at: 0, effectiveRange: nil) as? NSParagraphStyle { assert(!paragraphStyle.textLists.isEmpty) } else { assertionFailure("Paragraph has lost its text lists") } return paragraph }
0
0
89
May ’25
Custom, Markdown autocapitalizationType.
Hi, I've got an app that displays markdown in UITextView / NSTextView. I would like it to behave like Notes app does, that is if user types the line start modifier, e.g: "# " or "> " I would like the keyboard to show a capitalized letters. I've tried looking into overriding insertText - and it breaks the predictive text (can not insert white space). I've tried implementing UITextInputTokenizer but no luck either. Like I said, I see the Notes app does it perfectly, so maybe I'm missing something obvious or there is a way to do it without interrupting the auto-correction and predictive text. Ideally same thing can be applied to the NSTextView as the app support both platforms.
Topic: UI Frameworks SubTopic: UIKit Tags:
0
0
30
May ’25
The NSTextViewDelegate method textViewDidChangeSelection(:) will not fire, while all other text view delegate methods do.
I am trying to implement the NSTextViewDelegate function textViewDidChangeSelection(_ notification: Notification). My text view's delegate is the Coordinator of my NSViewRepresentable. I've found that this delegate function never fires, but any other delegate function that I implement, as long as it doesn't take a Notification as an argument, does fire (e.g., textView(:willChangeSelectionFromCharacterRange:toCharacterRange:), fires and is called on the delegate exactly when it should be). For context, I've verified all of the below: textView.isSelectable = true textView.isEditable = true textView.delegate === my coordinator I can call textViewDidChangeSelection(:) directly on the delegate without issue. I can select and edit text without issues. I.e., the selections are being set correctly. But the delegate method is never called when they are. I am able to add the intended delegate as an observer for the selector textViewDidChangeSelection via NotificationCenter. If I do this, the function executes when it should, but fires for every text view in my view hierarchy, which can number in the hundreds. I'm using an NSLayoutManager, so I figure this should only fire once. I've added a check within my code: func textViewDidChangeSelection(_ notification: Notification) { guard let textView = notification.object as? NSTextView, textView === layoutManager.firstTextView else { return } // Any code I want to execute... } But the above guard check lets through every notification, so, no matter what, my closure executes hundreds of times if I have hundreds of text views, all of them being sent by textView === layoutManager.firstTextView, but once for each and every text view managed by that layoutManager. Does anyone know why this method isn't ever called on the delegate, while seemingly all other delegate methods are? I could go the NotificationCenter route, but I'd love to know why this won't execute as a delegate method when documentation says that it should, and I don't want to have to implement a counter to make sure my code only executes once per selection update. And for more reasons than that, implementing via delegate method is preferable to using notifications for my use case. Thanks for any help!
3
0
120
May ’25
NSLayoutManager Bug -- layout manager re-laying out overlapping text into the same container.
I've posted a couple times now about major issues I'm having with NSLayoutManager and have written to Apple for code-level support, but no one at Apple has responded to me in more than two weeks. So I'm turning to the community again for any help whatsoever. I'm fairly certain it's a real bug in TextKit. If I'm right about that, I'd love for anyone at Apple to take an interest. And better yet, if I'm wrong (and I hope I am), I'd be incredibly grateful to anyone who can point out where my mistake lies! I've been stuck with this bug for weeks on end. The crux of the issue is that I'm getting what seemed to be totally incompatible results from back to back calls to textContainer(forGlyphAt:effectiveRange:) and lineFragmentRect(forGlyphAt:effectiveRange:withoutAdditionalLayout:)... I'd lay out my text into a fairly tall container of standard page width and then query the layout manager for the text container and line fragment rect for a particular glyph (a glyph that happens to fall after many newlines). Impossibly, the layout manager would report that that glyph was in said very tall container, but that the maxY of its lineFragmentRect was only at 14 points (my NSTextView's isFlipped is true, so that's 14 points measuring from the top down). After investigating, it appears that what is happening under the hood is NSLayoutManager is for some reason laying out text back into the first container in my series of containers, rather than overflowing it into the next container(s) and/or giving me a nil result for textContainer(forGlyphAt:...) I've created a totally stripped down version of my project that recreates this issue reliably and I'm hoping literally anyone at Apple will respond to me. In order to recreate the bug, I've had to build a very specific set of preview data - namely some NSTextStorage content and a unique set of NSTextViews / NSTextContainers. Because of the unique and particular setup required to recreate this bug, the code is too much to paste here (my preview data definition is a little unwieldy but the code that actually processes/parses it is not). I can share the project if anyone is able and willing to look into this with me. It seems I'm not able to share a .zip of the project folder here but am happy to email or share a dropbox link.
7
0
146
May ’25
How do I size a UITextView with scroll disabled?
tl;dr: UITextView does not auto layout when isScrollEnabled = false I have a screen with multiple UITextViews on it, contained within a ScrollView. For each textview, I calculate the height needed to display the entire content in SwiftUI and set it using the .frame(width:height:) modifier. The UITextView will respect the size passed in and layout within the container, but since UITextView is embedded within a UIScrollView, when a user attempts to scroll on the page, often they will scroll within a UITextView block rather than the page. They currently need to scroll along the margins outside of the textview to get the proper behavior. Since I am already calculating the height to display the text, I don't want the UITextView to scroll. However, when I set isScrollEnabled = false, the text view displays in a single long line that gets truncated. I have tried Setting various frame/size attributes but that seems to have zero affect on the layout. Embedding the textView within a UIView, and then sizing the container, but then the textView does not display at all. Setting a fixed size textContainer in the layoutManager but did not work. There's a lot of code so I can't copy/paste it all, but generally, it looks like struct SwiftUITextEditor: View { @State var text: AttributedString = "" var body: some View { ZStack { MyTextViewRepresentable(text: $text) } .dynamicallySized(from: $text) } } struct MyTextViewRepresentable: UIViewRepresentable { @Binding var text: AttributedString let textView = UITextView(usingTextLayoutManager: true) func makeUIView(context: Context) -> UITextView { textView.attributedText = text textView.isScrollEnabled = false } ... }
1
0
70
May ’25
Get NSTextView selection frame with NSTextLayoutManager
I'm trying to update my app to use TextKit 2. The one thing that I'm still not sure about is how I can get the selection frame. My app uses it to auto-scroll the text to keep the cursor at the same height when the text wraps onto a new line or a newline is manually inserted. Currently I'm using NSLayoutManager.layoutManager!.boundingRect(forGlyphRange:in:). The code below almost works. When editing the text or changing the selection, the current selection frame is printed out. My expectation is that the selection frame after a text or selection change should be equal to the selection frame before the next text change. I've noticed that this is not always true when the text has a NSParagraphStyle with spacing > 0. As long as I type at the end of the text, everything's fine, but if I insert some lines, then move the selection somewhere into the middle of the text and insert another newline, the frame printed after manually moving the selection is different than the frame before the newline is inserted. It seems that the offset between the two frames is exactly the same as the paragraph style's spacing. Instead when moving the selection with the arrow key the printed frames are correct. I've filed FB17104954. class ViewController: NSViewController, NSTextViewDelegate { private var textView: NSTextView! override func loadView() { let scrollView = NSScrollView(frame: CGRect(x: 0, y: 0, width: 400, height: 400)) textView = NSTextView(frame: scrollView.frame) textView.autoresizingMask = [.width, .height] textView.delegate = self let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.lineSpacing = 40 textView.typingAttributes = [.foregroundColor: NSColor.labelColor, .paragraphStyle: paragraphStyle] scrollView.documentView = textView scrollView.hasVerticalScroller = true view = scrollView } func textView(_ textView: NSTextView, shouldChangeTextIn affectedCharRange: NSRange, replacementString: String?) -> Bool { print("before", selectionFrame.maxY, selectionFrame) return true } func textDidChange(_ notification: Notification) { print("after ", selectionFrame.maxY, selectionFrame) } func textViewDidChangeSelection(_ notification: Notification) { print("select", selectionFrame.maxY, selectionFrame) } var selectionFrame: CGRect { guard let selection = textView.textLayoutManager!.textSelections.first?.textRanges.first else { return .null } var frame = CGRect.null textView.textLayoutManager!.ensureLayout(for: selection) textView.textLayoutManager!.enumerateTextSegments(in: selection, type: .selection, options: [.rangeNotRequired]) { _, rect, _, _ in frame = rect return false } return frame } }
0
1
66
Apr ’25
What is com.apple.TextInput.rdt?
Hello, community, I'm using an HTML editor in a .NET MAUI application running on macOS, and I'm encountering some unexpected behavior during text editing: Double-click text selection disappears after approximately one second. Styles randomly revert or are applied to the wrong text unexpectedly. It appears to be related to macOS spell checking. When using editable elements (, or with contenteditable), the system enables spell checking by default. During this, MAUI attempts to communicate with a system process: com.apple.TextInput.rdt, which is not running, leading to repeated errors like: Error Domain=NSCocoaErrorDomain Code=4099 "The connection to service named com.apple.TextInput.rdt was invalidated: failed at lookup with error 3 - No such process." Question: What is com.apple.TextInput.rdt, and why might it not be running? Thank you for any help!
2
0
72
Mar ’25
I want to know how to use TextKit2 to achieve the same functionality as the following code?
The main function of this code is that when I click on the link within the TextView, the TextView will respond to the event, while when clicking on other places, the TextView will not respond to the event. I want to know how to use TextKit2 to achieve the same functionality as the following code? class MyTextView: UITextView { override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? { var location = point location.x -= textContainerInset.left location.y -= textContainerInset.top let characterIndex = layoutManager.characterIndex(for: location, in: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if characterIndex < textStorage.length, characterIndex >= 0 { if let _ = textStorage.attribute(.link, at: characterIndex, effectiveRange: nil) { return self } } return nil } } I haven't found a method similar to that in Textkit1 within Textkit2. I'm looking forward to everyone's guidance.
Topic: UI Frameworks SubTopic: UIKit Tags:
1
0
84
Mar ’25
Hide characters with TextKit 2
With TextKit 1, I was able to “tag” characters with attribute string keys that flagged them to be invisible, then I would use NSLayoutManager’s layoutManager(_:shouldGenerateGlyphs:properties:characterIndexes:font:forGlyphRange:) to strip these characters out, preventing change to the underlying storage. In TextKit 2, I don’t see an opportunity to do this. The best point I think to intercept would be NSTextLayoutFragment, but without being able to see what’s happening, I don’t know if it’s possible to alter the content used to generate the line fragments. My end goal is to be able to hide characters for a Markdown editor, so maybe I’m thinking about this wrong? Any advice would be welcome.
1
0
286
Mar ’25
NSTextLineFragment crash - how to debug
We have crash reports as shown below that we haven't yet been able to repro and could use some help deubgging. My guess is that the app is giving a label or text view an attributed string with an invalid attribute range, but attributed strings are used in many places throughout the app, and I don't know an efficient way to track this down. I'm posting the stack trace here in hopes that someone more familiar with the internals of the system frameworks mentioned will be able to provide a clue to help narrow where I should look. Fatal Exception: NSRangeException NSMutableRLEArray objectAtIndex:effectiveRange:: Out of bounds 0 CoreFoundation 0x2d5fc __exceptionPreprocess 1 libobjc.A.dylib 0x31244 objc_exception_throw 2 Foundation 0x47130 blockForLocation 3 UIFoundation 0x2589c -[NSTextLineFragment _defaultRenderingAttributesAtCharacterIndex:effectiveRange:] 4 UIFoundation 0x25778 __53-[NSTextLineFragment initWithAttributedString:range:]_block_invoke 5 CoreText 0x58964 TLine::DrawGlyphsWithAttributeOverrides(TLineDrawContext const&, __CFDictionary const* (long, CFRange*) block_pointer, TDecoratorObserver*) const 6 CoreText 0x58400 CTLineDrawWithAttributeOverrides 7 UIFoundation 0x25320 _NSCoreTypesetterRenderLine 8 UIFoundation 0x24b10 -[NSTextLineFragment drawAtPoint:graphicsContext:] 9 UIFoundation 0x3e634 -[NSTextLineFragment drawAtPoint:inContext:] 10 UIFoundation 0x3e450 -[NSTextLayoutFragment drawAtPoint:inContext:] 11 UIKitCore 0x3e3098 __38-[_UITextLayoutFragmentView drawRect:]_block_invoke 12 UIKitCore 0x3e31cc _UITextCanvasDrawWithFadedEdgesInContext 13 UIKitCore 0x3e3040 -[_UITextLayoutFragmentView drawRect:] 14 UIKitCore 0xd7a98 -[UIView(CALayerDelegate) drawLayer:inContext:] 15 QuartzCore 0x109340 CABackingStoreUpdate_ 16 QuartzCore 0x109224 invocation function for block in CA::Layer::display_() 17 QuartzCore 0x917f0 -[CALayer _display] 18 QuartzCore 0x90130 CA::Layer::layout_and_display_if_needed(CA::Transaction*) 19 QuartzCore 0xe50c4 CA::Context::commit_transaction(CA::Transaction*, double, double*) 20 QuartzCore 0x5bd8c CA::Transaction::commit() 21 UIKitCore 0x9f3f0 _UIApplicationFlushCATransaction 22 UIKitCore 0x9c89c __setupUpdateSequence_block_invoke_2 23 UIKitCore 0x9c710 _UIUpdateSequenceRun 24 UIKitCore 0x9f040 schedulerStepScheduledMainSection 25 UIKitCore 0x9cc5c runloopSourceCallback 26 CoreFoundation 0x73f4c __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 27 CoreFoundation 0x73ee0 __CFRunLoopDoSource0 28 CoreFoundation 0x76b40 __CFRunLoopDoSources0 29 CoreFoundation 0x75d3c __CFRunLoopRun 30 CoreFoundation 0xc8284 CFRunLoopRunSpecific 31 GraphicsServices 0x14c0 GSEventRunModal 32 UIKitCore 0x3ee674 -[UIApplication _run] 33 UIKitCore 0x14e88 UIApplicationMain also filed as FB16905066
3
0
251
Mar ’25
NSTextView doesn't correctly redraw when deleting text and setting attribute at the same time
It seems that NSTextView has an issue with deleting text and setting any attribute at the same time, when it also has a textContainerInset. With the code below, after 1 second, the empty line in the text view is automatically deleted and the first line is colored red. The top part of the last line remains visible at its old position. Selecting the whole text and then deselecting it again makes the issue disappear. Is there a workaround? I've created FB16897003. class ViewController: NSViewController { @IBOutlet var textView: NSTextView! override func viewDidAppear() { textView.textContainerInset = CGSize(width: 0, height: 8) let _ = textView.layoutManager textView.textStorage!.setAttributedString(NSAttributedString(string: "1\n\n2\n3\n4")) textView.textStorage!.addAttribute(.foregroundColor, value: NSColor.labelColor, range: NSRange(location: 0, length: textView.textStorage!.length)) DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in textView.selectedRange = NSRange(location: 3, length: 0) textView.deleteBackward(nil) textView.textStorage!.beginEditing() textView.textStorage!.addAttribute(.foregroundColor, value: NSColor.red, range: NSRange(location: 0, length: 2)) textView.textStorage!.endEditing() } } }
5
0
211
Apr ’25
NSTextAttachment lagging in textkit 2
I have an attributedString with 100 NSTextAttachments(contains image of 400kb). When i scroll the textview, it is lagging, When i did the same in textkit 1, it is butter smooth. It can be because of how textkit 1 & 2 layout the elements. let attachment = NSTextAttachment() attachment.image = UIImage(named: "image2") let attachmentString = NSAttributedString(attachment: attachment) let mutableAttributedString = NSMutableAttributedString(attributedString: textView.attributedText) for _ in 0...100 { mutableAttributedString.append(NSAttributedString(string: "\n")) mutableAttributedString.append(attachmentString) } textView.attributedText = mutableAttributedString How to handle images in textkit 2 so that it feels smooth while scrolling textview?
1
0
441
Feb ’25