Problem
I want to be able to pass the text attributes from the selected range of the textView.textStorage and/or the typing attributes from the textView. This should happen when the selection changes.
The goal of this is so that the SwiftUI view can update based on the attributes being used by the user.
I am trying to do this with the textViewDidChangeSelection
method. However with NSTextViewDelegate I only get the selected range and can't pass any values stored from the textView in it.
My attempt
Below is a stripped down version of my RepresentableView.
import SwiftUI
struct TextViewMacOS: NSViewRepresentable {
@Binding var currentTypingAttributes: [NSAttributedString.Key : Any]
@Binding var currentTextAttributes: [NSAttributedString.Key : Any]
class Coordinator: NSObject, NSTextViewDelegate {
var parent: TextViewMacOS
init(_ parent: TextViewMacOS) {
self.parent = parent
}
func textViewDidChangeSelection(_ notification: Notification) {
/*
// Trying to do something like below:
// parent.currentTypingAttributes = textView.typingAttributes
// parent.currentTextAttributes = textView.textStorage?.attributes(at: textView.selectedRange().lowerBound, effectiveRange: nil)
*/
}
}
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
public func makeNSView(context: Context) -> NSTextView {
//[...]
}
public func updateNSView(_ textView: NSTextView, context: Context) {
//[...]
}
}
Is it possible to create a custom method that subscribes to the same notification but passes a textView? Do I have to make a custom Delegate?
Any help would be greatly appreciated. Cheers.