SwiftUI Text Editor Crash with Apple Pencil Long Press

Using Apple Pencil with SwiftUI text editor, when the user presses and holds in the middle of text already in the editor box a crash occurs. This is very reproducible even on this minimal example.

import SwiftUI
   
struct ContentView: View {
    
 @State private var text: String = "The quick brown fox jumps over the lazy dog"
        
 var body: some View {
   VStack {
     TextEditor(text: $text)
      .background(Color.init(red: 242, green: 242, blue: 242))
      .border(.black)
      .frame(height: 200)
    }
    .padding()
  }
}

When tapping and holding somewhere in the middle of the sentence, for example on the word "jumps" the app crashes with an exception reading: Thread 1: "NSTextContentStorage: Inconsistent element cache state. Elements for range {0, 43} are already cached while trying to insert"

The stack trace is:

I have attempted to use the approach discussed in this post to make the underlying UITextView use TextKit 1, but could find no UITextView in the underlying UIView hierarchy. Any advice would be greatly appreciated.

We experienced this same crash as of iOS 16 and still in iOS 16.3.

Long pressing an Apple Pencil inside a UITextView (instantiated in code) causes Scribble to sometimes insert a long wrapped--almost 2 lines--of blanks, after which there is a short delay and crash with exception "...Inconsistent element cache state...".

This crash can be prevented by changing the layout manager of the UITextView from TextKit 2 (now the iOS 16 default) to TextKit 1, which is done strangely enough by simply accessing the UITextView.layoutManager property as described in Apple's source code:

// To ensure compatibility with older code, accessing the .layoutManager 
// of a UITextView - or its .textContainer's .layoutManager - will cause 
// a UITextView that's using TextKit 2 to 'fall back' to TextKit 1, and 
// return a newly created NSLayoutManager. After this happens, 
// .textLayoutManager will return nil - and _any TextKit 2 objects you 
// may have cached will cease functioning_. Be careful about this if you 
// are intending to be using TextKit 2!
@property(nonatomic, readonly) NSLayoutManager *layoutManager API_AVAILABLE(ios(7.0));

NOTE that this does stop the strange insertion of the extra long blank lines, but instead just makes those blanks vanish when the pencil touches down again.

I encountered the same problem,use: textView.layoutManager.allowsNonContiguousLayout = false

I really don't understand why this is happening, it has been bothering me for too long!

SwiftUI Text Editor Crash with Apple Pencil Long Press
 
 
Q