Create own UILexicon entries

1.4k views Asked by At

I tried to subclass UILexicon so I could create my own entries in the init part. However, the entries array is read only. How can I create my own source of words for my custom predictive bar in a keyboard extension (iOS 8)?

1

There are 1 answers

0
SafeFastExpressive On

It doesn't appear that Apple designed UILexicon and UILexiconEntry to be mutable or create mutable copies. I'm developing in Swift, and it's implementation doesn't allow instantiation of new UILexiconEntry objects, and though I can instantiate a new UILexicon object, I can't add to it's entries list.

So it seems reasonable that the Objective C interfaces behave similarly, and the documentation supports this stating "Apple intends for you to consider the words in a lexicon object as supplementary to an autocorrection/suggestion lexicon of your own design."

Fortunately creating your own storage for Lexicon Entries is very simple, a NSDictionary can directly store them. Start by loading it with entries from the existing UILexicon list, using the userInput string as the key for each entry, and item.userInput string as the object. Here is an example in Swift, that should be readable for an objective C developer.

var myLexicon = NSMutableDictionary()

self.requestSupplementaryLexiconWithCompletion { (theLexicon: UILexicon!) -> Void in
   let lexiconEntries = theLexicon.entries

   // Completion handler
   for item in lexiconEntries {
         myLexicon.setObject(item.documentText, forKey: item.userInput)
    }
 }

Note that duplicate entries are filtered out of the Lexicons by using an NSDictionary, but this shouldn't be a problem because every userInput should output to only one documentText.