我有一个 NSTextField,我想启用“键入时”拼写检查。当我加载应用程序时,我可以通过菜单栏 > 编辑 > 拼写和语法 > 键入时检查拼写来执行此操作。
我希望默认启用此选项。在 IB 中,我可以为 NSTextView 启用此功能,但我想将 NSTextField 用于 UI 的这一部分。
谢谢。
Update:有谁知道是否可以通过 Objective-C 代码在 NSTextField 上以编程方式运行“菜单栏”>“编辑”>“拼写和语法”>“键入时检查拼写”选项? NSTextField 似乎支持“键入时检查拼写”选项,只是无法从 Obj-C 启用该选项。
Edit #1
我尝试了以下方法来手动启用菜单,但没有成功:
// Focus TextField
[textField becomeFirstResponder];
// Enable Spell Checking
NSMenu *mainMenu = [[NSApplication sharedApplication] mainMenu];
NSMenu *editMenu = [[mainMenu itemWithTitle:@"Edit"] submenu];
NSMenu *spellingMenu = [[editMenu itemWithTitle:@"Spelling and Grammar"] submenu];
NSMenuItem *autoSpellingMenuItem = [spellingMenu itemWithTitle:@"Check Spelling While Typing"];
[autoSpellingMenuItem setEnabled:YES];
NSLog(@"Menu: %@", [autoSpellingMenuItem description]);
NSLog(@"Target: %@", [[autoSpellingMenuItem target] description]);
// Actually perform menu action
[[autoSpellingMenuItem target] performSelector:[autoSpellingMenuItem action]];
是否无法直接调用菜单项操作而不使用 setEnabled:YES ?
上面的输出如下,不确定为什么目标为空
App[3895:a0f] Menu: <NSMenuItem: 0x100135180 Check Spelling While Typing>
Current language: auto; currently objective-c
App[3895:a0f] Target: (null)
SOLUTION
如果其他人需要知道,以下是此问题的解决方案。一些 NSLogging 向我展示,将 NSTextField 设置为 firstResponder 后,firstResponder 实际上包含一个 NSTextView,然后您可以启用拼写。我假设 NSTextField 在子视图中包含一个 NSTextView ,它接受响应者,实际上这应该在 NSTextField 类中公开。
// Focus TextField
[textField becomeFirstResponder];
// Enable Continous Spelling
NSTextView *textView = (NSTextView *)[self.window firstResponder];
[textView setContinuousSpellCheckingEnabled:YES];