NSTextField - 使选定的文本变为粗体、斜体或下划线?
我有一个 NSTextField,用户可以在其中写入文本。我希望能够制作3个按钮:粗体、斜体和下划线;这些按钮应将文本字段中的用户选择更改为粗体、斜体或下划线。
谁能指导我如何做到这一点?
I have an NSTextField where the user can write text. I would like to be able to make 3 buttons: bold, italic and underline; these buttons should change the user selection in the textfield to either bold, italic or underline.
Can anyone give me a pointer on how to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先是启用富文本支持,您可以在 Interface Builder 中通过检查检查器中的“富文本”选项来完成此操作,也可以使用
setAllowsEditingTextAttributes:
通过代码来实现。然后就是 NSAttributedString 了。
但最大的问题是,看起来您需要对所选文本应用更改。对于
NSTextField
来说这是不可能的。仅适用于NSTextView
。如果你能改变它,那就继续吧,事情会让事情变得更容易。但是,如果您确实需要坚持使用
NSTextField
,您可能需要访问字段编辑器。每个窗口都有一个关联的窗口,它是在幕后处理文本的窗口。然后就可以愉快的调用NSTextView的方法
setSelectedTextAttributes:
了。了解有关字段编辑器的更多信息 Apple 和CocoaDev
The first thing is to enable rich text support, and you can do it either in Interface Builder by checking the "Rich Text" option in the inspector or by code using
setAllowsEditingTextAttributes:
.Then it's all about
NSAttributedString
s.The big problem though is that looks like you need to apply changes to the selected text. This is not possible with
NSTextField
s. Only withNSTextView
s.If you can change it, go ahead and it will make things easier. However, if you do need to stick with
NSTextField
you may want to access the field editor. Each window has one associated, and it's what process the text behind the scenes.Then you can call NSTextView's method
setSelectedTextAttributes:
happily.Read more about the field editor here at Apple and in CocoaDev
假设您的 NSTextfield * 是 textField,下面的代码会为所选内容加下划线:
Assuming your NSTextfield * is textField, the code below underlines the selection: