How to get the selected line range of NSTextView?

无人久伴 提交于 2019-12-10 09:26:33

问题


How to get the selected line range of NSTextView?


回答1:


An outline algorithm for you:

  1. get the selection - selectedRange
  2. create a range of length 1 covering the last char of the selection
  3. use lineRangeForRange to obtain a range for the characters making up the line the last char of the selection is in.
  4. now work backwards and count - you've got the range of the line containing the last char of the selection, make a range for the last char of the preceding line and use lineRangeForRange to find the range for the preceding line. Repeat this process until you reach the start of the text. You'll have the line number of the last character in the original selection.
  5. During the above for every line range you produce check if the starting location of the selection is in that line. Note the current line count - which started at zero for the line containing the last char of the selection and is increasing as you progress to the start of the text. When the iteration of (4) is finished simple math gives you the line number of the first char.

Of course you could work the other way around - start with the line range for the first char in the text and work forward. For every line checking whether the start/end of the selection is in that line, stopping when you've found the line containing the end of the selection.

For code which does the reverse - given a range of lines it produces a selection to cover them - see Apple's TextEdit code sample, look at LinePanelController.m. Though this is doing the opposite of what you want reading it will show how the above mentioned methods work.

HTH.




回答2:


First, get the selected range through [textView selectedRange]
Then you can get the line range through - (NSRange)lineRangeForRange:(NSRange)range of [textView string]

NSRange sel = [textView selectedRange];
NSString *viewContent = [textView string];
NSRange lineRange = [viewContent lineRangeForRange:NSMakeRange(sel.location,0)];



回答3:


Have a look at the NSTextView documentation, there is a whole section devoted to dealing with text selections:

Such as selectedRanges



来源:https://stackoverflow.com/questions/16751130/how-to-get-the-selected-line-range-of-nstextview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!