NSTextField - 使选定的文本变为粗体、斜体或下划线?

发布于 2024-10-15 09:25:31 字数 109 浏览 4 评论 0原文

我有一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘虞初梦 2024-10-22 09:25:31

首先是启用富文本支持,您可以在 Interface Builder 中通过检查检查器中的“富文本”选项来完成此操作,也可以使用 setAllowsEditingTextAttributes: 通过代码来实现。

然后就是 NSAttributedString 了。

但最大的问题是,看起来您需要对所选文本应用更改。对于 NSTextField 来说这是不可能的。仅适用于 NSTextView

如果你能改变它,那就继续吧,事情会让事情变得更容易。但是,如果您确实需要坚持使用 NSTextField,您可能需要访问字段编辑器。每个窗口都有一个关联的窗口,它是在幕后处理文本的窗口。

NSTextView *editor = (NSTextView *)[window fieldEditor:YES forObject:myTextField]

然后就可以愉快的调用NSTextView的方法setSelectedTextAttributes:了。

了解有关字段编辑器的更多信息 AppleCocoaDev

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 NSAttributedStrings.

The big problem though is that looks like you need to apply changes to the selected text. This is not possible with NSTextFields. Only with NSTextViews.

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.

NSTextView *editor = (NSTextView *)[window fieldEditor:YES forObject:myTextField]

Then you can call NSTextView's method setSelectedTextAttributes: happily.

Read more about the field editor here at Apple and in CocoaDev

一片旧的回忆 2024-10-22 09:25:31

假设您的 NSTextfield * 是 textField,下面的代码会为所选内容加下划线:

NSMutableAttributedString * as = [[[textField attributedStringValue] mutableCopy] autorelease];
[as beginEditing];
[as addAttribute:NSUnderlineStyleAttributeName
           value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
           range:[[[textField window] fieldEditor:YES forObject:textField] selectedRange]];

[as endEditing];
[textField setAttributedStringValue:as];

Assuming your NSTextfield * is textField, the code below underlines the selection:

NSMutableAttributedString * as = [[[textField attributedStringValue] mutableCopy] autorelease];
[as beginEditing];
[as addAttribute:NSUnderlineStyleAttributeName
           value:[NSNumber numberWithInt:NSUnderlineStyleSingle]
           range:[[[textField window] fieldEditor:YES forObject:textField] selectedRange]];

[as endEditing];
[textField setAttributedStringValue:as];
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文