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

Posts under TextKit tag

176 Posts

Post

Replies

Boosts

Views

Activity

tracksTextAttachmentViewBounds not working
Hello :), I want to have a UIView inside of a UITextView. For that I use the new NSTextAttachmentViewProvider class introduced in iOS 15. The views width should always be equal to the width of the UITextView this width should update when, for example, the screen rotates. To do that I am using the tracksTextAttachmentViewBounds property inside of a NSTextAttachmentViewProvider subclass. If I understand correctly, if this property is set to true, the function attachmentBounds(for:location:textContainer:proposedLineFragment:position:) of my NSTextAttachmentViewProvider subclass should be used to determine the views bounds. In the code example below I have set it up in that manner, sadly the function is never called. (The storyboard consists of a UIViewController with a UITextView which four constrains (trailing, leading, bottom, top) are set equal to the safe area, nothing special going on). I have also tried to use a NSTextAttachment subclass in which I override the attachmentBounds(for:location:textContainer:proposedLineFragment:position:) function. It is also not called. The view is appearing, but not with the width and height that I have set in the function (see screenshot below), maybe it is using some default values. When I start typing, the view disappears. I don't know what I am doing wrong. Could somebody help me with that problem? import UIKit class SomeNSTextAttachmentViewProvider : NSTextAttachmentViewProvider { override func loadView() { super.loadView() tracksTextAttachmentViewBounds = true view = UIView() view!.backgroundColor = .purple } override func attachmentBounds( for attributes: [NSAttributedString.Key : Any], location: NSTextLocation, textContainer: NSTextContainer?, proposedLineFragment: CGRect, position: CGPoint ) -> CGRect { return CGRect(x: 0, y: 0, width: proposedLineFragment.width, height: 200) } } class ViewController: UIViewController { @IBOutlet var textView: UITextView? override func viewDidLoad() { super.viewDidLoad() NSTextAttachment.registerViewProviderClass(SomeNSTextAttachmentViewProvider.self, forFileType: "public.data") let mutableAttributedString = NSMutableAttributedString() mutableAttributedString.append(NSAttributedString("purple box: ")) mutableAttributedString.append( NSAttributedString( attachment: NSTextAttachment(data: nil, ofType: "public.data") ) ) textView?.attributedText = mutableAttributedString textView?.font = UIFont.preferredFont(forTextStyle: .body) } }
1
0
1.7k
Jun ’22
Crash at [NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixFontAttributeInRange:]
Hi, I am setting the attributed string to NSTextStorage and replacing it with another attributed string if need changes. I am getting crash with this stack trace: CoreFoundation CFCharacterSetIsLongCharacterMember + 0x28 UIFoundation -[NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixFontAttributeInRange:] + 0x15fc UIFoundation -[NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixAttributesInRange:] + 0x70 UIFoundation -[NSTextStorage processEditing] + 0xe0 UIFoundation -[NSTextStorage edited:range:changeInLength:] + 0x14c Foundation -[NSConcreteMutableAttributedString replaceCharactersInRange:withAttributedString:] + 0x158 UIFoundation __71-[NSConcreteTextStorage replaceCharactersInRange:withAttributedString:]_block_invoke + 0x28 UIFoundation __NSConcreteTextStorageLockedForwarding + 0x34 UIFoundation -[NSConcreteTextStorage replaceCharactersInRange:withAttributedString:] + 0x44 \ Please help with what could be the issue. I have checked that the attributed string is not nil and the font is UIFont *.
0
0
909
May ’22
UITextView rich text editing
I need to implement a text editor using UITextView that supports: Bold/Italic/Underline Color,Font,font size changes Paragraph alignment List format (bullets, numbers, etc.) Custom selection of text anywhere in the text view and change the properties So far I have managed to do it without NSTextStorage but it seems I am hitting limits. For instance, to change font, I use UIFontPickerViewController and change the font as follows: func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) { if let selectedFontDesc = viewController.selectedFontDescriptor { let font = UIFont(descriptor: selectedFontDesc, size: selectedFontDesc.pointSize) self.selectedFont = font self.textView.typingAttributes = [NSAttributedString.Key.foregroundColor: self.selectedColor ?? UIColor.white, NSAttributedString.Key.font: self.selectedFont ?? UIFont.preferredFont(forTextStyle: .body, compatibleWith: nil)] if let range = self.textView.selectedTextRange, let selectedFont = selectedFont { let attributedText = NSMutableAttributedString(attributedString: self.textView.attributedText) let location = textView.offset(from: textView.beginningOfDocument, to: range.start) let length = textView.offset(from: range.start, to: range.end) let nsRange = NSRange(location: location, length: length) attributedText.setAttributes([NSAttributedString.Key.font : selectedFont], range: nsRange) self.textView.attributedText = attributedText } } } This works but the problem is it resets the color of the selected text and other properties. I need to understand a way in which the existing attributed of the text under selection are not disturbed. I suspect the way to do is with using NSTextStorage but I can't find anything good on internet that explains the right use of NSTextStorage to achieve this.
1
0
1.5k
May ’22
UITextInput autocorrection: where do we receive text replaced by the system?
I have an implementation of UITextInput that is used to implement note taking with text. We have a custom UIMenuItem that lists suggested text replacements for a misspelled word that a user can interact with to fix the word. This works well on iPhone and iPad where the only path for changing text is via this menu. On Mac Catalyst, however, the system also presents text replacement options with the best replacement; and when users attempt to replace text with the menu options provided by the system, our UITextInput handler seems to only receive a call to setSelectedTextRange: (the code is in Objective-C). I would expect a call to, for example, replaceRange:WithText: after an autocorrection is made Any ideas what could possibly be incorrectly implementing? I.e., how can we receive the text that the system attempts to replace?
0
0
647
Apr ’22
Determining automatic scroll position in NSTextView
I have an NSTextView which uses syntax highlighting via textDidChange delegate method. Its contents are scaled using scaleUnitSquareToSize. Automatic scrolling works correctly when user reaches the bottom of the screen and line wraps — if this happens in the middle of the document. At the end, however, the scrolling seems to jump erratically for the first couple of characters. Causes of the issue I've tracked down the issue to a certain call order. Normally, textDidChange: is called between NSTextView keyDown: and NSClipView _scrollTo:, but not when the line gets so long it wraps. When typing will cause the line to wrap, the call stack looks like this (from bottom to top): [NSTextView adjustScroll:] [NSClipView _scrollTo:animateScroll:flashScrollerKnobs:] [NSTextView keyDown:] This is how it usually looks: [NSTextView adjustScroll:] [NSClipView _scrollTo:animateScroll:flashScrollerKnobs:] [Document textDidChange:] [NSTextView keyDown:] I have no idea how keyDown and _scrollTo determine where to scroll, but it seems that at some point, the text view scale is not taken into account, or gets calculated incorrectly. Solutions? I've tried wrapping my syntax highlighting in textStorage.beginEditing() and .endEditing(), which kind of fixes the issue, but also causes even more scrolling glitches when pressing space or deleting backwards. I also tried disabling adjustScroll in the text view while syntax highlighting has not yet taken place, but that, too, causes completely random jumps in scroll position, again when inserting a space or deleting. I'm trying to figure out how and where NSTextView determines the scroll position. There is no visible method in the call stack, but there has to be a method that checks if caret is in view and how to reposition content view's bounds, right? ...... Right? Any help or hints would be appreciated.
0
0
1k
Apr ’22
How Text Layout Manager generates Layout Fragment from Text Elements?
During the presentation (19:43) it says the NSTextLayoutFragment 'Layout information for one or more elements'. But from the documentation it seems that you can only generate a layout fragment from one NSTextElement. Besides there is only one property that associates a text element. What does it mean by 'parent element' anyway?
0
0
830
Apr ’22
NSTextCheckingClient example code?
I am trying to implement text checking in my custom text editor by implementing NSTextCheckingClient, but I can't get anything to work. And I can't find much documentation or any example code anywhere. I have created an example project here: https://github.com/jessegrosjean/NSTextInputClient
1
0
1k
Mar ’22
TextEditor automatically adjusts the height
Good day together, I am currently trying to adjust the height of my TextEditor automatically. The whole thing should not increase further once 3 lines are reached. The whole thing is modeled after the text field in the iMessage app. Now to my problem: I'm trying to recreate the whole thing in SwiftUI and so far it works quite well, but I currently have the problem that the height of the control is not automatically adjusted and I unfortunately do not know how to do it best. Does anyone have a suggestion or even a solution for this? SwiftUI Snippet: VStack{           List{           }.listStyle(.plain)           HStack(alignment: .center){             Button{                             }label:{               Image(systemName: "plus.circle")                 .resizable()                 .frame(width: 25, height: 25, alignment: .center)             }             HStack{               TextEditor(text: $message)                 .focused($focusedField, equals: .messageView_TextEditor)                 .foregroundColor(self.message == "Message" ? .gray : .primary)                 .frame(height:35.0)                 .onTapGesture {                   if self.message == "Message"{                     self.message = ""                   }                 }                 .padding(.leading,10)                               Button{                                 }label:{                 Image(systemName: "arrow.up.circle.fill")                   .resizable()                   .frame(width: 25, height: 25, alignment: .center)                   .padding(.trailing,5)                   .foregroundColor(.green)               }             }.overlay(               RoundedRectangle(cornerRadius: 8)                 .stroke(Color.gray, lineWidth: 1)             )           }           .padding(.bottom)                                 }
1
0
2k
Mar ’22
Replacing the NSLayoutManager for UITextView causes no text to be rendered in iOS 15
I have a simple project where I replace the NSLayoutManager for a UITextView initialized in a storyboard using UITextView.textContainer.replaceLayoutManager(…). On iOS 14.5, the layout manager is correctly replaced and the overridden drawUnderline function is called to correctly render the text using the subclassed NSLayoutManager. On iOS 15.2, none of the overridden functions in the NSLayoutManager subclass are being called, and no text is rendered in the UITextView. Custom NSLayoutManager: CaptionTextLayoutManager.swift ViewController: ViewController.swift Result (iOS 14.5 on the left, iOS 15.2 on the right): I think this is a regression in iOS 15 and not from my code, however I could be missing something.
0
0
1.7k
Mar ’22
Scrollable NSTextView with custom NSTextStorage for formatting
I'm trying to make a text editor with formatting for Mac OS. Which I have working using an NSTextView together with a custom NSTextStorage class. Which applies attributes like bold etc to NSAttributableStrings. This all seems to work fine as seen in screenshot one below. Which is an NSTextView with a custom NSTextStorage class attached to it. Which applies the formatting through attributes on an NSAttributeableString However, having everything the same, but getting a scrollable NSTextView from the Apple supplied function NSTextView.scrollableTextView() it does not display any text at all. Even though you can see in the screenshot that the NStextView is actually visible. Also, moving my mouse over the editor changes the cursor to the editor cursor. But I can't select, type or do anything. Doing the exact same thing as above, but not supplying a text container to the text view does show that it is wired up correctly, since I do get a scrollable text view then. Where the scrolling actually works, but then of course the formatting is no longer applied. So I'm confused on what I have to do now. This is basically my setup: // // TextDocumentViewController.swift // // Created by Matthijn on 15/02/2022. // Based on LayoutWithTextKit2 Sample from Apple import Foundation import AppKit class TextDocumentViewController: NSViewController { // Extends NSTextStorage, applies attributes to NSAttributeAbleString for formatting private var textStorage: TextStorage // Not custom yet, default implementation - do I need to subclass this specifically and implement something to support the scrolling behaviour? Which seems weird to me since it does work without scrolling support private var layoutManager: NSLayoutManager // Also default implementation private var textContainer: NSTextContainer private var textDocumentView: NSTextView private var scrollView: NSScrollView required init(content: String) { textStorage = TextStorage(editorAttributes: MarkdownAttributes) layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) textContainer = NSTextContainer() // I'm not 100% sure if I need this on false or true or can just do defaults. No combination fixes it // textContainer.heightTracksTextView = false // textContainer.widthTracksTextView = true layoutManager.addTextContainer(textContainer) scrollView = NSTextView.scrollableTextView() textDocumentView = (scrollView.documentView as! NSTextView) // Basically commenting this out, stops applying my NSTextContainer, NSLayoutManager and NSTextContainer, but then of course the formatting is not applied. This one line changes it between it works without formatting, or it doesn't work at all. (Unless I have my text view not embedded in a scroll view) then it works but the scrolling of course then does not work. textDocumentView.textContainer = textContainer textDocumentView.string = content textDocumentView.isVerticallyResizable = true textDocumentView.isHorizontallyResizable = false super.init(nibName: nil, bundle: nil) } override func loadView() { view = scrollView } }
0
0
1.5k
Feb ’22
NSTextView inspector bar not showing paragraph style and some other tools
The recent upgrade of the Mac OS seems to have removed some of the inspector bar tools from the NSTextView that formerly appears after setting usesInspectorBar to true. I see nothing in the documentation for any API for making these tools reappear. I notice that the TextEdit app's inspector bar is not missing them. Please tell me how to get my app's text view's inspector bar to look and behave like TextEdit.
1
0
914
Feb ’22
iOS15NSTextAttachment
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];      attachment.image = image;      attachment.bounds = CGRectMake(0, (font.capHeight - image.size.height) / 2, 15, image.size.height);      NSMutableAttributedString *imageString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
3
0
1.3k
Jan ’22
I am a new developer. How can i make my output text editable?
I have made a Scan to Text app with the help of sources from the internet, but I can’t figure out a way to get my output text to be editable. Here’s my code private func makeScannerView()-> ScannerView {         ScannerView(completion: {             textPerPage in             if let outputText = textPerPage?.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines){                 let newScanData = ScanData(content: outputText)                 self.texts.append(newScanData)             }             self.showScannerSheet = false                      })     }
0
0
752
Jan ’22
TextKit 2 Demo Question
Hi there, I have a small question regards to the TextKit 2 demo app: In macOS / TextDocumentView.swift / viewportBounds(for:) / Line 106 , why compare overdrawRect.minY with max(visibleRect.minY, 0)? Isn’t overdrawRect.minY always the smaller one (as it’s an overdraw rect)? Another question would be, if I'm planning to start working on an application with complex text editing features, would you recommend using NSTextView for now and wait for further updates, or just use the TextKit 2 stack (with CALayers) like the one used in the demo? I really love TextKit 2 and so far the demo seems pretty performant. But I don't know if there is any drawbacks if I build a TextKit 2 stack on my own so I'm looking forward to your advice. Many thanks
0
0
987
Dec ’21
NSInternalInconsistencyException
We are facing the below crash quite for some days, With key NSInternalInconsistencyException, after our users got updated their OS to iOS 15, for earlier versions it works fine without any crash. We are clueless as nothing in the stack call our native code and each line in the stack relates to UI. this issue is happening for most of our users repeatedly, we tried various scenarios but unable to find the root cause. Similar issues have found in the forum when upgrading from iOS 12 to 13 but they related to threading issues, this is of a kind range exception, please do the needful. Appreciate your help in advance. Fatal Exception: NSInternalInconsistencyException out of bounds characterRange {0, 0} specified to _drawTexCorrectionMarker:characterRange:atOrigin:graphicsContext: Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x9905c __exceptionPreprocess 1 libobjc.A.dylib 0x15f54 objc_exception_throw 2 Foundation 0x13099c _userInfoForFileAndLine 3 UIFoundation 0xa933c -[NSTextLineFragment _drawTexCorrectionMarker:characterRange:atOrigin:graphicsContext:] 4 UIFoundation 0x8b08 -[NSTextLineFragment drawTextCorrectionMarkersAtPoint:graphicsContext:] 5 UIFoundation 0x65c44 -[NSTextLineFragment drawAtPoint:graphicsContext:] 6 UIFoundation 0x69ef4 -[NSTextLineFragment drawAtPoint:inContext:] 7 UIFoundation 0x3eb80 -[NSTextLayoutFragment drawAtPoint:inContext:] 8 UIKitCore 0x649ce4 _UITextCanvasDrawWithFadedEdgesInContext 9 UIKitCore 0x77cb4c -[_UITextLayoutFragmentView drawRect:] 10 UIKitCore 0x188930 -[UIView(CALayerDelegate) drawLayer:inContext:] 11 QuartzCore 0x4d2c8 CABackingStoreUpdate_ 12 QuartzCore 0x8fe60 invocation function for block in CA::Layer::display_() 13 QuartzCore 0x91ae0 -[CALayer _display] 14 QuartzCore 0x31bc4 CA::Layer::layout_and_display_if_needed(CA::Transaction*) 15 QuartzCore 0x460b0 CA::Context::commit_transaction(CA::Transaction*, double, double*) 16 QuartzCore 0x4f174 CA::Transaction::commit() 17 QuartzCore 0x3121c CA::Transaction::flush_as_runloop_observer(bool) 18 UIKitCore 0x544c28 _UIApplicationFlushCATransaction 19 UIKitCore 0x7dead8 _UIUpdateSequenceRun 20 UIKitCore 0xe56294 schedulerStepScheduledMainSection 21 UIKitCore 0xe55760 runloopSourceCallback 22 CoreFoundation 0xbb030 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 23 CoreFoundation 0xcbcf0 __CFRunLoopDoSource0 24 CoreFoundation 0x5ff8 __CFRunLoopDoSources0 25 CoreFoundation 0xb804 __CFRunLoopRun 26 CoreFoundation 0x1f3c8 CFRunLoopRunSpecific 27 GraphicsServices 0x138c GSEventRunModal 28 UIKitCore 0x51b060 -[UIApplication _run] 29 UIKitCore 0x298b8c UIApplicationMain 30 mobilex 0x41673c (Missing) 31 User Mobile 0x25f18 main + 43 (main.m:43) 32 ??? 0x1056f9a24 (Missing)
7
1
4.5k
Dec ’21
Where is the sample code for TextKitAndTextViewSampleApp?
I just watched the WWDC22 video: "What's new in Textkit and text views" but don't see a resource link for the sample code for TextKitAndTextViewSampleApp. Does anyone have the link for this sample code?
Replies
1
Boosts
2
Views
952
Activity
Jun ’22
tracksTextAttachmentViewBounds not working
Hello :), I want to have a UIView inside of a UITextView. For that I use the new NSTextAttachmentViewProvider class introduced in iOS 15. The views width should always be equal to the width of the UITextView this width should update when, for example, the screen rotates. To do that I am using the tracksTextAttachmentViewBounds property inside of a NSTextAttachmentViewProvider subclass. If I understand correctly, if this property is set to true, the function attachmentBounds(for:location:textContainer:proposedLineFragment:position:) of my NSTextAttachmentViewProvider subclass should be used to determine the views bounds. In the code example below I have set it up in that manner, sadly the function is never called. (The storyboard consists of a UIViewController with a UITextView which four constrains (trailing, leading, bottom, top) are set equal to the safe area, nothing special going on). I have also tried to use a NSTextAttachment subclass in which I override the attachmentBounds(for:location:textContainer:proposedLineFragment:position:) function. It is also not called. The view is appearing, but not with the width and height that I have set in the function (see screenshot below), maybe it is using some default values. When I start typing, the view disappears. I don't know what I am doing wrong. Could somebody help me with that problem? import UIKit class SomeNSTextAttachmentViewProvider : NSTextAttachmentViewProvider { override func loadView() { super.loadView() tracksTextAttachmentViewBounds = true view = UIView() view!.backgroundColor = .purple } override func attachmentBounds( for attributes: [NSAttributedString.Key : Any], location: NSTextLocation, textContainer: NSTextContainer?, proposedLineFragment: CGRect, position: CGPoint ) -> CGRect { return CGRect(x: 0, y: 0, width: proposedLineFragment.width, height: 200) } } class ViewController: UIViewController { @IBOutlet var textView: UITextView? override func viewDidLoad() { super.viewDidLoad() NSTextAttachment.registerViewProviderClass(SomeNSTextAttachmentViewProvider.self, forFileType: "public.data") let mutableAttributedString = NSMutableAttributedString() mutableAttributedString.append(NSAttributedString("purple box: ")) mutableAttributedString.append( NSAttributedString( attachment: NSTextAttachment(data: nil, ofType: "public.data") ) ) textView?.attributedText = mutableAttributedString textView?.font = UIFont.preferredFont(forTextStyle: .body) } }
Replies
1
Boosts
0
Views
1.7k
Activity
Jun ’22
Crash at [NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixFontAttributeInRange:]
Hi, I am setting the attributed string to NSTextStorage and replacing it with another attributed string if need changes. I am getting crash with this stack trace: CoreFoundation CFCharacterSetIsLongCharacterMember + 0x28 UIFoundation -[NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixFontAttributeInRange:] + 0x15fc UIFoundation -[NSMutableAttributedString(NSMutableAttributedStringKitAdditions) fixAttributesInRange:] + 0x70 UIFoundation -[NSTextStorage processEditing] + 0xe0 UIFoundation -[NSTextStorage edited:range:changeInLength:] + 0x14c Foundation -[NSConcreteMutableAttributedString replaceCharactersInRange:withAttributedString:] + 0x158 UIFoundation __71-[NSConcreteTextStorage replaceCharactersInRange:withAttributedString:]_block_invoke + 0x28 UIFoundation __NSConcreteTextStorageLockedForwarding + 0x34 UIFoundation -[NSConcreteTextStorage replaceCharactersInRange:withAttributedString:] + 0x44 \ Please help with what could be the issue. I have checked that the attributed string is not nil and the font is UIFont *.
Replies
0
Boosts
0
Views
909
Activity
May ’22
UITextView rich text editing
I need to implement a text editor using UITextView that supports: Bold/Italic/Underline Color,Font,font size changes Paragraph alignment List format (bullets, numbers, etc.) Custom selection of text anywhere in the text view and change the properties So far I have managed to do it without NSTextStorage but it seems I am hitting limits. For instance, to change font, I use UIFontPickerViewController and change the font as follows: func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) { if let selectedFontDesc = viewController.selectedFontDescriptor { let font = UIFont(descriptor: selectedFontDesc, size: selectedFontDesc.pointSize) self.selectedFont = font self.textView.typingAttributes = [NSAttributedString.Key.foregroundColor: self.selectedColor ?? UIColor.white, NSAttributedString.Key.font: self.selectedFont ?? UIFont.preferredFont(forTextStyle: .body, compatibleWith: nil)] if let range = self.textView.selectedTextRange, let selectedFont = selectedFont { let attributedText = NSMutableAttributedString(attributedString: self.textView.attributedText) let location = textView.offset(from: textView.beginningOfDocument, to: range.start) let length = textView.offset(from: range.start, to: range.end) let nsRange = NSRange(location: location, length: length) attributedText.setAttributes([NSAttributedString.Key.font : selectedFont], range: nsRange) self.textView.attributedText = attributedText } } } This works but the problem is it resets the color of the selected text and other properties. I need to understand a way in which the existing attributed of the text under selection are not disturbed. I suspect the way to do is with using NSTextStorage but I can't find anything good on internet that explains the right use of NSTextStorage to achieve this.
Replies
1
Boosts
0
Views
1.5k
Activity
May ’22
Soft hyphen is not working properly in iOS 15
label.text = "Very\u{00AD}VeryVeryVeryVeryVeryLongWordWithASoftHyphenTo"
Replies
5
Boosts
0
Views
4.2k
Activity
May ’22
UITextInput autocorrection: where do we receive text replaced by the system?
I have an implementation of UITextInput that is used to implement note taking with text. We have a custom UIMenuItem that lists suggested text replacements for a misspelled word that a user can interact with to fix the word. This works well on iPhone and iPad where the only path for changing text is via this menu. On Mac Catalyst, however, the system also presents text replacement options with the best replacement; and when users attempt to replace text with the menu options provided by the system, our UITextInput handler seems to only receive a call to setSelectedTextRange: (the code is in Objective-C). I would expect a call to, for example, replaceRange:WithText: after an autocorrection is made Any ideas what could possibly be incorrectly implementing? I.e., how can we receive the text that the system attempts to replace?
Replies
0
Boosts
0
Views
647
Activity
Apr ’22
Determining automatic scroll position in NSTextView
I have an NSTextView which uses syntax highlighting via textDidChange delegate method. Its contents are scaled using scaleUnitSquareToSize. Automatic scrolling works correctly when user reaches the bottom of the screen and line wraps — if this happens in the middle of the document. At the end, however, the scrolling seems to jump erratically for the first couple of characters. Causes of the issue I've tracked down the issue to a certain call order. Normally, textDidChange: is called between NSTextView keyDown: and NSClipView _scrollTo:, but not when the line gets so long it wraps. When typing will cause the line to wrap, the call stack looks like this (from bottom to top): [NSTextView adjustScroll:] [NSClipView _scrollTo:animateScroll:flashScrollerKnobs:] [NSTextView keyDown:] This is how it usually looks: [NSTextView adjustScroll:] [NSClipView _scrollTo:animateScroll:flashScrollerKnobs:] [Document textDidChange:] [NSTextView keyDown:] I have no idea how keyDown and _scrollTo determine where to scroll, but it seems that at some point, the text view scale is not taken into account, or gets calculated incorrectly. Solutions? I've tried wrapping my syntax highlighting in textStorage.beginEditing() and .endEditing(), which kind of fixes the issue, but also causes even more scrolling glitches when pressing space or deleting backwards. I also tried disabling adjustScroll in the text view while syntax highlighting has not yet taken place, but that, too, causes completely random jumps in scroll position, again when inserting a space or deleting. I'm trying to figure out how and where NSTextView determines the scroll position. There is no visible method in the call stack, but there has to be a method that checks if caret is in view and how to reposition content view's bounds, right? ...... Right? Any help or hints would be appreciated.
Replies
0
Boosts
0
Views
1k
Activity
Apr ’22
How Text Layout Manager generates Layout Fragment from Text Elements?
During the presentation (19:43) it says the NSTextLayoutFragment 'Layout information for one or more elements'. But from the documentation it seems that you can only generate a layout fragment from one NSTextElement. Besides there is only one property that associates a text element. What does it mean by 'parent element' anyway?
Replies
0
Boosts
0
Views
830
Activity
Apr ’22
NSTextCheckingClient example code?
I am trying to implement text checking in my custom text editor by implementing NSTextCheckingClient, but I can't get anything to work. And I can't find much documentation or any example code anywhere. I have created an example project here: https://github.com/jessegrosjean/NSTextInputClient
Replies
1
Boosts
0
Views
1k
Activity
Mar ’22
TextEditor automatically adjusts the height
Good day together, I am currently trying to adjust the height of my TextEditor automatically. The whole thing should not increase further once 3 lines are reached. The whole thing is modeled after the text field in the iMessage app. Now to my problem: I'm trying to recreate the whole thing in SwiftUI and so far it works quite well, but I currently have the problem that the height of the control is not automatically adjusted and I unfortunately do not know how to do it best. Does anyone have a suggestion or even a solution for this? SwiftUI Snippet: VStack{           List{           }.listStyle(.plain)           HStack(alignment: .center){             Button{                             }label:{               Image(systemName: "plus.circle")                 .resizable()                 .frame(width: 25, height: 25, alignment: .center)             }             HStack{               TextEditor(text: $message)                 .focused($focusedField, equals: .messageView_TextEditor)                 .foregroundColor(self.message == "Message" ? .gray : .primary)                 .frame(height:35.0)                 .onTapGesture {                   if self.message == "Message"{                     self.message = ""                   }                 }                 .padding(.leading,10)                               Button{                                 }label:{                 Image(systemName: "arrow.up.circle.fill")                   .resizable()                   .frame(width: 25, height: 25, alignment: .center)                   .padding(.trailing,5)                   .foregroundColor(.green)               }             }.overlay(               RoundedRectangle(cornerRadius: 8)                 .stroke(Color.gray, lineWidth: 1)             )           }           .padding(.bottom)                                 }
Replies
1
Boosts
0
Views
2k
Activity
Mar ’22
Replacing the NSLayoutManager for UITextView causes no text to be rendered in iOS 15
I have a simple project where I replace the NSLayoutManager for a UITextView initialized in a storyboard using UITextView.textContainer.replaceLayoutManager(…). On iOS 14.5, the layout manager is correctly replaced and the overridden drawUnderline function is called to correctly render the text using the subclassed NSLayoutManager. On iOS 15.2, none of the overridden functions in the NSLayoutManager subclass are being called, and no text is rendered in the UITextView. Custom NSLayoutManager: CaptionTextLayoutManager.swift ViewController: ViewController.swift Result (iOS 14.5 on the left, iOS 15.2 on the right): I think this is a regression in iOS 15 and not from my code, however I could be missing something.
Replies
0
Boosts
0
Views
1.7k
Activity
Mar ’22
Scrollable NSTextView with custom NSTextStorage for formatting
I'm trying to make a text editor with formatting for Mac OS. Which I have working using an NSTextView together with a custom NSTextStorage class. Which applies attributes like bold etc to NSAttributableStrings. This all seems to work fine as seen in screenshot one below. Which is an NSTextView with a custom NSTextStorage class attached to it. Which applies the formatting through attributes on an NSAttributeableString However, having everything the same, but getting a scrollable NSTextView from the Apple supplied function NSTextView.scrollableTextView() it does not display any text at all. Even though you can see in the screenshot that the NStextView is actually visible. Also, moving my mouse over the editor changes the cursor to the editor cursor. But I can't select, type or do anything. Doing the exact same thing as above, but not supplying a text container to the text view does show that it is wired up correctly, since I do get a scrollable text view then. Where the scrolling actually works, but then of course the formatting is no longer applied. So I'm confused on what I have to do now. This is basically my setup: // // TextDocumentViewController.swift // // Created by Matthijn on 15/02/2022. // Based on LayoutWithTextKit2 Sample from Apple import Foundation import AppKit class TextDocumentViewController: NSViewController { // Extends NSTextStorage, applies attributes to NSAttributeAbleString for formatting private var textStorage: TextStorage // Not custom yet, default implementation - do I need to subclass this specifically and implement something to support the scrolling behaviour? Which seems weird to me since it does work without scrolling support private var layoutManager: NSLayoutManager // Also default implementation private var textContainer: NSTextContainer private var textDocumentView: NSTextView private var scrollView: NSScrollView required init(content: String) { textStorage = TextStorage(editorAttributes: MarkdownAttributes) layoutManager = NSLayoutManager() textStorage.addLayoutManager(layoutManager) textContainer = NSTextContainer() // I'm not 100% sure if I need this on false or true or can just do defaults. No combination fixes it // textContainer.heightTracksTextView = false // textContainer.widthTracksTextView = true layoutManager.addTextContainer(textContainer) scrollView = NSTextView.scrollableTextView() textDocumentView = (scrollView.documentView as! NSTextView) // Basically commenting this out, stops applying my NSTextContainer, NSLayoutManager and NSTextContainer, but then of course the formatting is not applied. This one line changes it between it works without formatting, or it doesn't work at all. (Unless I have my text view not embedded in a scroll view) then it works but the scrolling of course then does not work. textDocumentView.textContainer = textContainer textDocumentView.string = content textDocumentView.isVerticallyResizable = true textDocumentView.isHorizontallyResizable = false super.init(nibName: nil, bundle: nil) } override func loadView() { view = scrollView } }
Replies
0
Boosts
0
Views
1.5k
Activity
Feb ’22
NSTextView inspector bar not showing paragraph style and some other tools
The recent upgrade of the Mac OS seems to have removed some of the inspector bar tools from the NSTextView that formerly appears after setting usesInspectorBar to true. I see nothing in the documentation for any API for making these tools reappear. I notice that the TextEdit app's inspector bar is not missing them. Please tell me how to get my app's text view's inspector bar to look and behave like TextEdit.
Replies
1
Boosts
0
Views
914
Activity
Feb ’22
Seeking WWDC 2010 video & transcript, "Advanced Cocoa Text Tips and Tricks"
TextKit Best Practices (WWDC 2018) mentions the 2010 session, but I cannot find it on Apple's website. Help?
Replies
1
Boosts
0
Views
802
Activity
Feb ’22
Seeking WWDC 2013 video & transcript, "Advanced Layouts and Effects With Text Kit"
There are references in more recent WWDC sessions, but it's no longer on Apple's website. Help!
Replies
1
Boosts
0
Views
870
Activity
Feb ’22
iOS15NSTextAttachment
NSTextAttachment *attachment = [[NSTextAttachment alloc] init];      attachment.image = image;      attachment.bounds = CGRectMake(0, (font.capHeight - image.size.height) / 2, 15, image.size.height);      NSMutableAttributedString *imageString = [[NSAttributedString attributedStringWithAttachment:attachment] mutableCopy];
Replies
3
Boosts
0
Views
1.3k
Activity
Jan ’22
I am a new developer. How can i make my output text editable?
I have made a Scan to Text app with the help of sources from the internet, but I can’t figure out a way to get my output text to be editable. Here’s my code private func makeScannerView()-> ScannerView {         ScannerView(completion: {             textPerPage in             if let outputText = textPerPage?.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines){                 let newScanData = ScanData(content: outputText)                 self.texts.append(newScanData)             }             self.showScannerSheet = false                      })     }
Replies
0
Boosts
0
Views
752
Activity
Jan ’22
TextKit 2 Demo Question
Hi there, I have a small question regards to the TextKit 2 demo app: In macOS / TextDocumentView.swift / viewportBounds(for:) / Line 106 , why compare overdrawRect.minY with max(visibleRect.minY, 0)? Isn’t overdrawRect.minY always the smaller one (as it’s an overdraw rect)? Another question would be, if I'm planning to start working on an application with complex text editing features, would you recommend using NSTextView for now and wait for further updates, or just use the TextKit 2 stack (with CALayers) like the one used in the demo? I really love TextKit 2 and so far the demo seems pretty performant. But I don't know if there is any drawbacks if I build a TextKit 2 stack on my own so I'm looking forward to your advice. Many thanks
Replies
0
Boosts
0
Views
987
Activity
Dec ’21
NSInternalInconsistencyException
We are facing the below crash quite for some days, With key NSInternalInconsistencyException, after our users got updated their OS to iOS 15, for earlier versions it works fine without any crash. We are clueless as nothing in the stack call our native code and each line in the stack relates to UI. this issue is happening for most of our users repeatedly, we tried various scenarios but unable to find the root cause. Similar issues have found in the forum when upgrading from iOS 12 to 13 but they related to threading issues, this is of a kind range exception, please do the needful. Appreciate your help in advance. Fatal Exception: NSInternalInconsistencyException out of bounds characterRange {0, 0} specified to _drawTexCorrectionMarker:characterRange:atOrigin:graphicsContext: Fatal Exception: NSInternalInconsistencyException 0 CoreFoundation 0x9905c __exceptionPreprocess 1 libobjc.A.dylib 0x15f54 objc_exception_throw 2 Foundation 0x13099c _userInfoForFileAndLine 3 UIFoundation 0xa933c -[NSTextLineFragment _drawTexCorrectionMarker:characterRange:atOrigin:graphicsContext:] 4 UIFoundation 0x8b08 -[NSTextLineFragment drawTextCorrectionMarkersAtPoint:graphicsContext:] 5 UIFoundation 0x65c44 -[NSTextLineFragment drawAtPoint:graphicsContext:] 6 UIFoundation 0x69ef4 -[NSTextLineFragment drawAtPoint:inContext:] 7 UIFoundation 0x3eb80 -[NSTextLayoutFragment drawAtPoint:inContext:] 8 UIKitCore 0x649ce4 _UITextCanvasDrawWithFadedEdgesInContext 9 UIKitCore 0x77cb4c -[_UITextLayoutFragmentView drawRect:] 10 UIKitCore 0x188930 -[UIView(CALayerDelegate) drawLayer:inContext:] 11 QuartzCore 0x4d2c8 CABackingStoreUpdate_ 12 QuartzCore 0x8fe60 invocation function for block in CA::Layer::display_() 13 QuartzCore 0x91ae0 -[CALayer _display] 14 QuartzCore 0x31bc4 CA::Layer::layout_and_display_if_needed(CA::Transaction*) 15 QuartzCore 0x460b0 CA::Context::commit_transaction(CA::Transaction*, double, double*) 16 QuartzCore 0x4f174 CA::Transaction::commit() 17 QuartzCore 0x3121c CA::Transaction::flush_as_runloop_observer(bool) 18 UIKitCore 0x544c28 _UIApplicationFlushCATransaction 19 UIKitCore 0x7dead8 _UIUpdateSequenceRun 20 UIKitCore 0xe56294 schedulerStepScheduledMainSection 21 UIKitCore 0xe55760 runloopSourceCallback 22 CoreFoundation 0xbb030 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ 23 CoreFoundation 0xcbcf0 __CFRunLoopDoSource0 24 CoreFoundation 0x5ff8 __CFRunLoopDoSources0 25 CoreFoundation 0xb804 __CFRunLoopRun 26 CoreFoundation 0x1f3c8 CFRunLoopRunSpecific 27 GraphicsServices 0x138c GSEventRunModal 28 UIKitCore 0x51b060 -[UIApplication _run] 29 UIKitCore 0x298b8c UIApplicationMain 30 mobilex 0x41673c (Missing) 31 User Mobile 0x25f18 main + 43 (main.m:43) 32 ??? 0x1056f9a24 (Missing)
Replies
7
Boosts
1
Views
4.5k
Activity
Dec ’21
Text with line numbers in TextKit 2
What is the recommended approach to rendering text with line numbers in TextKit 2?
Replies
3
Boosts
0
Views
3.1k
Activity
Dec ’21