0

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.

santi.gs
  • 514
  • 3
  • 15
  • 1
    Not clear what do you meant by `and can't pass any values`? Getting `textViewDidChangeSelection` you have access to everything from sender textView (which is `notification.object`). – Asperi Dec 19 '20 at 14:58
  • Hi @Aspperi, the apple docs say the notification value from textViewDidChangeSelection is an NSRange. https://developer.apple.com/documentation/appkit/nstextview/1449275-didchangeselectionnotification. How can i accesss the textView from the notification? – santi.gs Dec 19 '20 at 15:03
  • 1
    notification.object is a sender NSTextView – Asperi Dec 19 '20 at 15:11

0 Answers0