如何使用UITextChecker查找拼写错误的单词

问题描述 投票:0回答:2

我想使用 UITextChecker 来查找错误的单词。不幸的是,我的代码没有按我的预期工作。有人可以纠正我的错误吗?

import UIKit

func isCorrect(word: String) -> Bool {
    let checker = UITextChecker ()
    let range = NSRange(location: 0, length: word.utf16.count)
    let misspelledRange = checker.rangeOfMisspelledWord(
        in: word,
        range: range,
        startingAt: 0,
        wrap: false,
        language: "en"
    )
    return misspelledRange.location == NSNotFound
}

print(isCorrect(word: "apple"))
print(isCorrect (word: "ppale"))

谢谢你帮助我。

ios swift uikit misspelling uitextchecker
2个回答
2
投票

您的代码工作正常

func isCorrect(word:String)->Bool{
    let checker = UITextChecker()
    let range = NSRange(location: 0, length: word.utf16.count)
    let mispelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")

    return mispelledRange.location == NSNotFound
}

print(isCorrect(word: "apple"))
print(isCorrect(word: "ppale"))

enter image description here


0
投票

在这里您可以找到

UITextChecker

的示例

考虑下面的例子:

func isReal(word: String) -> Bool {
    let checker = UITextChecker()
    let range = NSRange(location: 0, length: word.utf16.count)
    let misspelledRange = checker.rangeOfMisspelledWord(in: word, range: range, startingAt: 0, wrap: false, language: "en")

    return misspelledRange.location == NSNotFound
}

isReal(word: "apple") //true
isReal(word: "pple")  //false
© www.soinside.com 2019 - 2024. All rights reserved.