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

Posts under TextKit tag

165 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.9k
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
1.2k
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.7k
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
761
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
1.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
1k
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
1.2k
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
2.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.8k
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.6k
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
1.3k
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.5k
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
1.1k
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
1.1k
Dec ’21
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.9k
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
1.2k
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.7k
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
761
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
1.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
1k
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
1.2k
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
2.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.8k
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.6k
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
1.3k
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.5k
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
1.1k
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
1.1k
Activity
Dec ’21