Search code examples
iosswiftcocoa-touchuitextview

Updating UITextView autocapitalizationType dynamically


I've got a blank test application with a UITextView, and I've added this delegate method:

func textViewDidChange(textView: UITextView) {
    if textView.text.hasPrefix("Cap") {
        textView.autocapitalizationType = .AllCharacters
    } else {
        textView.autocapitalizationType = .Sentences
    }
}

If the user types "Cap" at the start of the text, I want the textView to change to the .AllCharacters autocapitalizationType. If they remove that prefix, it should change back to sentences.

The code is called but not honoured and the keyboard doesn't change to reflect this. Any idea how I can nudge the textView to update the caps?


Solution

  • Resigning first responder to force the autocapitalizationType change to take effect isn't very clean. Instead, call UITextView.reloadInputViews() after changing autocapitalizationType. The keyboard stays open and uses the new autocapitalizationType value. According to the reloadInputViews() docs:

    You can use this method to refresh the custom input view or input accessory view associated with the current object when it is the first responder. The views are replaced immediately—that is, without animating them into place.

    That's exactly what I needed to temporarily select the shift key on the keyboard.