我有一個NSTextField,我想啓用「as-you-type」拼寫檢查。當我加載我的應用程序時,我可以從菜單欄中執行此操作>編輯>拼寫和語法>在鍵入時檢查拼寫。如何在Mac OS X的NSTextField中啓用拼寫檢查?
我想這個選項默認啓用。在IB內部,我可以爲NSTextView啓用此功能,但是我想爲這部分用戶界面使用NSTextField。
謝謝。
更新:有誰知道是否可以通過Objective-C代碼以編程方式運行菜單欄>編輯>拼寫和語法>檢查時正在拼寫的拼寫選項嗎?看起來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)
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];
出現的'NSTextView'被稱爲字段編輯器。如果這個'firstResponder'轉換太脆弱了,你可以在'NSWindowController'中重寫'-windowWillReturnFieldEditor:forObject:',並在那裏改變設置。 – ctietze 2017-06-13 07:28:06