I want to use the autocorrection and shortcut list like default English keyboard with my custom keyboard. I check the in keyboard document but don\'t know how to use it.
Rachits answer above in swift 4. Works with iOS 12
I have this helper to check wether the current string to be tested by UITextChecker is not a space
func validate(string: String?) -> Bool {
guard let text = string,
!text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {
return false
}
return true
}
The text checker is then in my "Spacebar", "Spacebar double tapped" & "return" methods. The example below is in my "Space" method
let textChecker = UITextChecker()
let currentString = self.textDocumentProxy.documentContextBeforeInput
if validate(string: currentString) {
let charSet = NSCharacterSet.whitespacesAndNewlines
let components = currentString?.components(separatedBy: charSet)
let lastWord = components?.last
let checkRange = NSMakeRange(0, lastWord?.count ?? 0)
let misspelledRange = textChecker.rangeOfMisspelledWord(in: lastWord!, range: checkRange, startingAt: checkRange.location, wrap: false, language: "en_US")
if misspelledRange.length != 0 {
let guessedWord: Array = textChecker.guesses(forWordRange: misspelledRange, in: lastWord!, language: "en_US")!
if guessedWord.count > 0 {
var i = 0
while (lastWord?.length)! > i {
textDocumentProxy.deleteBackward()
i += 1
}
self.textDocumentProxy.insertText(guessedWord[0])
}
}
}
self.textDocumentProxy.insertText(" ")
I had to make two changes to Rachits code. First to validate the currentString since it throws an exception if you press space bar twice. And second to check if the misspelled range is not 0 because that was also throwing an exception which I am yet to figure out why. But this works for me now as is.