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"
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:
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.