I tried to wrap NSTextView using TextKit 2 into NSViewRepresentable, so I can use it on SwiftUI. But when I try to access textLayoutManager
and textContentStorage
, they are always nil
import Foundation
import SwiftUI
import Cocoa
struct Editor_macOS: NSViewRepresentable {
func makeNSView(context: Context) -> NSScrollView {
let textContainer = NSTextContainer(size: .zero)
context.coordinator.textLayoutManager.textContainer = textContainer
let textView = NSTextView(frame: .zero, textContainer: textContainer)
context.coordinator.textView = textView
if let docURL = Bundle.main.url(forResource: "menu", withExtension: "rtf") {
do {
print(textView.textLayoutManager)
// try textView.textContentStorage!.textStorage?.read(from: docURL, documentAttributes: nil, error: ())
} catch {
// Could not read menu content.
}
}
textView.isRichText = false
textView.font = NSFont.monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular)
textView.autoresizingMask = [.width]
textView.translatesAutoresizingMaskIntoConstraints = true
textView.isVerticallyResizable = true
textView.isHorizontallyResizable = false
let scrollView = NSTextView.scrollableTextView()
scrollView.hasVerticalScroller = true
scrollView.drawsBackground = false
context.coordinator.scrollView = scrollView
return scrollView
}
func updateNSView(_ nsView: NSScrollView, context: Context) {
}
class Coordinator: NSObject {
var parent: Editor_macOS
var textView: NSTextView?
let textLayoutManager = NSTextLayoutManager()
init(_ parent: Editor_macOS) {
self.parent = parent
}
}
func makeCoordinator() -> Editor_macOS.Coordinator {
Editor_macOS.Coordinator(self)
}
typealias NSViewType = NSScrollView
}
Does anyone have an ideal why is it?