objective-c - NSTextView 暂时禁用自动拼写更正

标签 objective-c cocoa nstextview

问题

在某些应用程序中,例如邮件客户端或 Twitter 客户端,我发现自己正在打字,一切看起来都很好,当我按下发送/推文按钮时, TextView 会自动将最后一个单词纠正为不正确的拼写。显然,当时我在完成打字后等待了错误的时间才发送,因此拼写检查仍在继续。

我想这里的第一个问题确实应该是您对删除该功能有何看法?因为另一方面,我确信人们也会发生完全相同的事情,但它实际上修复了最后一个单词的拼写,而不是弄乱它。否则,如果您认为这是一个有效的想法,是否有办法在 NSTextView 失去焦点时禁用自动拼写纠正?

我看过的内容:

我实际尝试过的内容(在空项目的 Xcode 中)

  • 实现NSTextDelegate textShouldBeginEditing:textShouldEndEditing: 以及调用内部 [self.textView setAutomaticSpellingCorrectionEnabled:true];[self.textView setAutomaticSpellingCorrectionEnabled:false ]; 分别(起初我还调用了 NSTextViewsetAutomaticTextReplacementEnabled: 但这仅适用于用户设置,例如 (c) 到版权符号)

  • 在同一个 textShouldBeginEditing:textShouldEndEditing:(从上面)中设置 NSTextViewenabledTextCheckingTypes 分别为 NSTextCheckingAllTypesNSTextCheckingAllTypes - NSTextCheckingTypeCorrection

  • 子类化 NSTextView 并实现 becomeFirstResponderresignFirstResponder 并在其中更改与上面相同的属性。

    <
  • resignFirstRespondertextShouldEndEditing: 调用 NSSpellChecker 方法(这适用于 [[NSSpellChecker sharedSpellChecker] DismissCorrectionIndicatorForView: self];)隐藏弹出窗口,但它仍然会纠正拼写)

示例

我在 Tweetbot 中注意到了此功能你可以使用foreign vsforeign来测试它。如果您在气泡仍然存在时输入并发布推文,它将发布错误的拼写。

最佳答案

解决方案是子类化 NSTextView 并重写 handleTextCheckingResults: 方法。

- (void)handleTextCheckingResults:(NSArray<NSTextCheckingResult *> *)results forRange:(NSRange)range types:(NSTextCheckingTypes)checkingTypes options:(NSDictionary<NSTextCheckingOptionKey,id> *)options orthography:(NSOrthography *)orthography wordCount:(NSInteger)wordCount {
    for (NSTextCheckingResult *result in results) {
        if (result.resultType == NSTextCheckingTypeSpelling) {
            // you can either suppress all corrections by using `return` here

            // or you can compare the original string to the replacement like this:
            NSString *originalString = [self.string substringWithRange:result.range];
            NSString *replacement = result.replacementString;

            // or you can do something more complex (like suppressing correction only under
            // certain conditions

            return; // we don't do the correction
        }
    }

    // default behaviors, including auto-correct
    [super handleTextCheckingResults:results forRange:range types:checkingTypes options:options orthography:orthography wordCount:wordCount];
}

这适用于所有 NSTextCheckingType。

关于objective-c - NSTextView 暂时禁用自动拼写更正,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14866512/

相关文章:

ios - UISearchDisplayController 不更新搜索结果

iphone - ABPeoplePickerNavigationController 隐藏取消按钮

ios - 如何使用 setKeepAliveTimeout :handler - IOS?

objective-c - CorePlot 图形计算器不在 (0;0) 点开始

cocoa - 处理 NSCell 上的鼠标悬停(NSTextAttachmentCell)

objective-c - 如何让 NSTextView 随文本一起增长?

objective-c - 从 JSON 数组 objective-c 获取值时出现问题

swift - 如何在应用程序包之外的 AVPlayer 中播放视频文件

objective-c - Cocoa中的CMD+Option+D模拟

swift - NSTextView:应用段落样式