如何获取NSTextView的选定行范围? [英] How to get the selected line range of NSTextView?

查看:441
本文介绍了如何获取NSTextView的选定行范围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取 NSTextView

推荐答案

您的大纲算法:


  1. 获取选择 - selectedRange

  2. 使用 lineRangeForRange 创建覆盖所选内容的最后一个字符的长度1的范围


  3. 现在向后倒计数 - 您已经得到了包含选择的最后一个字符的行的范围,为前一行的最后一个字符创建一个范围,并使用 lineRangeForRange 查找上一行的范围。重复此过程,直到到达文本的开始。

  4. 在上面的每一行范围内,您都将检查选择的起始位置是否在该行中。注意当前行计数 - 从包含选择的最后一个字符的行开始为零,并且随着进行到文本的开始而增加。

  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.

反之 - 给定范围的行,它产生一个选择覆盖它们 - 参见Apple的 TextEdit代码示例,查看 LinePanelController.m 。虽然这与你想要阅读的方式相反,但它会显示上述方法的工作原理。

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。

这篇关于如何获取NSTextView的选定行范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆