Search code examples
iosswiftcustom-keyboardautocapitalize

Custom keyboard auto capitalization


I would like to adopt the TextField's AutocapitalizationType settings to the custom keyboard. How do I know when to capitalize the keyboard while typing?

I searched for solutions and examples, I looked through the Apple Developer Documentation, but I can't find it


Solution

  • You have to analyze the text around the current insertion point and capitalize accordingly.

    • .none: Simple, never capitalize.
    • .words: If the character before the insertion point is a space and maybe a hyphen. Also if at the start.
    • .sentences: If the insertion point is preceded by white space and end of sentence punctuation (period, question mark, exclamation, etc.) or if at the start.
    • .allCharacters: Simple - always capitalize.

    Of course these rules may vary based on language.

    You can see some of the text before the insertion point using textDocumentProxy.documentContextBeforeInput.

    Some of the answers found at Swift: Split String into sentences might prove helpful.

    There is also iOS Custom Keyboard Extension auto capitalization which has some ideas as well.