如何在Mac OS X上的NSTextField中启用拼写检查?

时间:2010-05-13 08:17:13

标签: objective-c cocoa macos spell-checking nstextfield

我有一个NSTextField,我想启用“as-you-type”拼写检查。当我加载我的应用程序时,我可以从菜单栏>编辑>拼写和语法>键入时检查拼写。

我希望默认情况下启用此选项。在IB中,我可以为NSTextView启用此功能,但我想在此部分UI中使用NSTextField。

谢谢。

更新:是否有人知道是否可以以编程方式运行菜单栏>编辑>拼写和语法>从Objective-C代码检查NSTextField上的拼写选项时的拼写?似乎NSTextField支持“在键入时检查拼写”选项,只是没有办法从Obj-C启用该选项。

编辑#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)

如果其他人需要知道,以下是此问题的解决方案。一些NSLogging告诉我,在将NSTextField设置为firstResponder之后,firstResponder实际上包含NSTextView,然后您可以启用拼写。我假设NSTextField在子视图中包含一个NSTextView,它接收响应者,实际上这应该在NSTextField类中公开。

// Focus TextField
[textField becomeFirstResponder];

// Enable Continous Spelling
NSTextView *textView = (NSTextView *)[self.window firstResponder];
[textView setContinuousSpellCheckingEnabled:YES];

2 个答案:

答案 0 :(得分:4)

你很幸运,Apple提供了一个拼写检查课:NSSpellChecker:

http://developer.apple.com/mac/library/documentation/cocoa/Conceptual/SpellCheck/Concepts/SpellChecker.html

使用此功能,您可以在每次用户使用textdidChange委托方法更新文本时检查拼写。

另外,您说要使用NSTextField而不是NSTextView。为什么不使用可编辑的NSTextView来设置toggleAutomaticSpellingCorrection属性?

编辑:

要以编程方式更改菜单项的值,请执行以下操作:

// 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];

// Actually perform menu action
[[autoSpellingMenuItem target] performSelector:[autoSpellingMenuItem action]];

编辑:

看起来上面的方法实际上并没有像预期的那样触发该方法,并且目标是NULL(因为第一个响应者还没有被设置?)。但是可以直接发送消息,如下所示:

// Focus TextField
[textField becomeFirstResponder];

// Enable Continous Spelling
NSTextView *textView = (NSTextView *)[self.window firstResponder];
[textView setContinuousSpellCheckingEnabled:YES];

答案 1 :(得分:1)

您是否尝试过使用NSTextField委托方法textDidChange: 并致电:

range = [[NSSpellChecker sharedSpellChecker] checkSpellingOfString:aString startingAt:0];

每一次?