如何从我的 NSTextField 获取突出显示的文本?
这肯定很容易,但我没有在文档中找到任何内容。 我需要的行为与右键单击文本的任何部分然后可以对其执行某些操作完全相同。 目前我有一个自己的自定义 NSTextField 类,它重新实现“mouseDown”操作。这部分有效!我以为我可以通过“theEvent”获得 nstextfield 的选定文本部分,但显然这是不可能的。
It must be certainly easy but I haven't found anything in the doc.
The behavior I need is exactly as when you right-click any portion of text and then you can do some action with it.
For the moment I have a my own custom NSTextField class which re-implment 'mouseDown' action. This part works ! I thought I could get the selected portion of text of my nstextfield thanks to 'theEvent' but apparently it is not possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我实际上认为你不能用 NSTextField 做到这一点。我认为您必须改用 NSTextView,然后使用
-selectedRanges
方法。编辑:我应该说,你不能直接执行此操作(即,没有 NSTextField 方法可以执行此操作)。我认为,您必须使用与窗口关联的字段编辑器(它本身就是一个 NSTextView)才能执行此操作。 这是苹果使用指南字段编辑器。
I don't actually think you can do this with NSTextField. I think you have to use an NSTextView instead and then make use of the
-selectedRanges
method.EDIT: I should have said, you can't do this directly (i.e., there's no NSTextField method for doing this). I think rather, you have to use the field editor (which is itself an NSTextView) associated with the window in order to do this. Here's the apple guide for using the field editor.
添加到 @Sean 的答案,我使用以下解决方案来获取/更改 NSTextField 的选定文本:
如果此函数返回
NO
,则没有字段编辑器(文本字段可能没有焦点)或不选择。Adding to @Sean 's answer, I use the following solution to get/change the selected text of an NSTextField:
If this function returns
NO
, there is either no field editor (the text field may not have focus) or no selection.NSTextField
内部使用了NSTextView
,因此我们可以找到该文本视图,然后使用其公共 API 获取选择范围,然后计算所选文本。 (在 macOS 13.5.2 上测试)查看层次结构:
NSTextField
internally usesNSTextView
, so we can just find that text view, then use its public API to get the selection range, then calculate the selected text. (Tested on macOS 13.5.2)View hierarchy: