I am trying to implement the NSTextViewDelegate function textViewDidChangeSelection(_ notification: Notification)
. My text view's delegate is the Coordinator of my NSViewRepresentable. I've found that this delegate function never fires, but any other delegate function that I implement, as long as it doesn't take a Notification as an argument, does fire (e.g., textView(:willChangeSelectionFromCharacterRange:toCharacterRange:), fires and is called on the delegate exactly when it should be).
For context, I've verified all of the below:
- textView.isSelectable = true
- textView.isEditable = true
- textView.delegate === my coordinator
- I can call textViewDidChangeSelection(:) directly on the delegate without issue.
- I can select and edit text without issues. I.e., the selections are being set correctly. But the delegate method is never called when they are.
I am able to add the intended delegate as an observer for the selector textViewDidChangeSelection via NotificationCenter. If I do this, the function executes when it should, but fires for every text view in my view hierarchy, which can number in the hundreds. I'm using an NSLayoutManager, so I figure this should only fire once. I've added a check within my code:
func textViewDidChangeSelection(_ notification: Notification) {
guard let textView = notification.object as? NSTextView,
textView === layoutManager.firstTextView else { return }
// Any code I want to execute...
}
But the above guard check lets through every notification, so, no matter what, my closure executes hundreds of times if I have hundreds of text views, all of them being sent by textView === layoutManager.firstTextView, but once for each and every text view managed by that layoutManager.
Does anyone know why this method isn't ever called on the delegate, while seemingly all other delegate methods are? I could go the NotificationCenter route, but I'd love to know why this won't execute as a delegate method when documentation says that it should, and I don't want to have to implement a counter to make sure my code only executes once per selection update. And for more reasons than that, implementing via delegate method is preferable to using notifications for my use case.
Thanks for any help!