iOS: Keyboard Shortcuts and Predictive Texts Customization

CHEN SU
CS Random Thoughts on Tech
3 min readMar 30, 2018

iOS keyboard has bunch of settings, and this article will talk about 2 options: “Shortcuts” and “Predictive”.

If user has turned on “Shortcuts” and “Predictive”, user will see an extra row on top of keyboard containing those supportive options. (“Shortcuts” is shown only on iPad)

As a developer, if you are building a component that want to have customized shortcuts and have control to show or hide the predictive texts, there’re some tricks to be careful about.

Basically there are 2 types of components accepts user inputs: TextField and WKWebView’s element (a contenteditable div for example).

Predictive Texts for TextField

TextField has an attribute “autocorrectionType” that controls the predictive texts, regardless what user sets in system settings.

textField.autocorrectionType = .no / .yes

Predictive Texts for WKWebView

For example, we have a contenteditable div shown in the webview, there’s an attribute “autocomplete” that could be added to div to control the predictive texts. WKWebView doesn’t have an attribute “autocorrectionType” like TextField, the attribute needs to apply to web elements to tell iOS to configure the keyboards.

Shortcuts for TextField

The key idea is to modify TextField.inputAssistantItem to control the keyboard shortcuts. You could clear its leadingBarButtonGroups and trailingBarButtonGroups, and append newly created groups, with UIBarButtonItem either in text format or image format.

Shortcuts for WKWebView

However, if you use the same mechanism to modify WKWebView’s inputAssistantItem, it only works the first time the keyboard is shown. The second time keyboard shows, default shortcuts are shown again.

To make your custom shortcuts shown in keyboard when editing in WKWebView, you need to modify the inputAssistantItem of WKWebView’s WKContentView. Add an observer to UIKeyboardDidShow, and make the change in the callback.

What I did is modify WKContentView’s inputAssistantItem in both viewDidLoad and UIKeyboardDidShow’s callback. Then my customized shortcuts remain in keyboard.

https://github.com/martinsuchen35/iOS-Keyboard-Shortcuts

Questions to Apple:

  1. What’s the difference those inputAssistantItem? What’s the best practice of when and where to use them?
  • UIViewController.inputAssistantItem
  • TextField.inputAssistantItem
  • WKWebView.inputAssistantItem

2. Should WKWebView’s inputAssistantItem be responsible for maintaining the states instead of using its WKContentView’s inputAssistantItem? Is it a bug that WKWebView’s inputAssistantItem only honors the change one time?

3. Bug has been reported to Apple https://bugreport.apple.com/web/?problemID=39105282

--

--