I need to use the length of NSRange of last selection in text (in NSTextView) before the text is changed. For this I am using the Notifications in following way:
override func viewDidLoad()
{
NotificationCenter.default.addObserver(self, selector: #selector(self.textIsChanged(_:)), name:NSText.didChangeNotification, object: myTextView)
NotificationCenter.default.addObserver(self, selector: #selector(self.textWillBeChanged(_:)), name:NSText.didBeginEditingNotification, object: myTextView)
}
var lengthOfSelection = Int()
@objc func textWillBeChanged(_ notification: Notification)
{
lengthOfSelection = myTextView.selectedRange().length
}
@objc func textIsChanged(_ notification: Notification)
{
lengthOfSelection //this variable is used here
}
The problem is that when text is selected and then deleted the value of lengthOfSelection
is not 100% correct in the function textIsChanged
. I.e. sometimes it is zero, while the selection of deleted text was not zero before the text has changed and lengthOfSelection
should not be zero.
Update.
I have found out from were I am getting the unexpected zero. It is the case when:
text from Pasteboard is inserted in a position (with zero length of selection) and then when I am deleting somewhere the selected part of the text I am getting the NSRange of the position where previous incertion was pasted. So it is actually not last selection, but one before the last.
Now the question is why? How can it be ? And, what can I do to get indeed the NSRange of the last selected text ?