1

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 ?

VYT
  • 1,071
  • 19
  • 35
  • When is `lengthOfSelection` set to zero? What are you trying to accomplish? `NSTextViewDelegate` has several methods to catch changes. – Willeke Jan 27 '20 at 11:37
  • @Willeke When I am deleting selected text I can get zero and this happens unpredictably, sometime correct, sometime zero. I need to know the NSRange of the previous selection right before the text is changed for downstream calculation taking place after text is changed. – VYT Jan 27 '20 at 12:14
  • How about [textView(_:shouldChangeTextInRanges:replacementStrings:)](https://developer.apple.com/documentation/appkit/nstextviewdelegate/1449206-textview)? – Willeke Jan 27 '20 at 12:28
  • @Willeke It is not suitable for me. – VYT Jan 27 '20 at 12:50
  • `.didBeginEditingNotification` is sent once when you start editing, not on every edit action. Why can't you use `textView(_:shouldChangeTextInRanges:replacementStrings:)`? – Willeke Jan 28 '20 at 10:46

0 Answers0