0

I have a NSTextView and I need to check if there is a selection, (blue highlight) of a word (or anything really), and not just a cursor. How can I do this. nil doesn't work, and I can't figure it out.

2 Answers2

2

There can be multiple selection in an NSTextView, the methods selectedRanges returns an array of all the selections. If there is just a cursor this method returns a single NSRange with the location giving where the cursor is and the length set to zero.

So your question can be answer with:

NSArray *allSelections = myTextView.selectedRanges;
BOOL hasSelection = allSelections.count > 1
                 || (allSelections.count == 1 && allSelections[0].length != 0);

HTH

CRD
  • 52,522
  • 5
  • 70
  • 86
0

You can use [NSTextView selectedRanges] method to see if there is a selection.

if (self.textView.selectedRanges.count > 0) {
    NSLog(@"Some text is selected!");
}

You may want to read the documentation for more information.

Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119
  • 1
    This is incorrect. If there is just an insertion point then `selectedRanges` returns a single range with a `length` of `0`. – CRD Feb 08 '15 at 18:59