Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
nathan Avatar asked Sep 05 '25 03:09

nathan


1 Answers

Very interesting question. In fact the autocapitalizationType doesn't change while the keyboard is present but you can nudge it by resigning it and making it become the first responder again:

textView.autocapitalizationType = .AllCharacters
// slow operation
textView.resignFirstResponder() 
textView.becomeFirstResponder()

The problem is this process is slow so you will feel a big delay between every character so you should do this operation once.

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

I hope that helps.

like image 60
Raphael Oliveira Avatar answered Sep 07 '25 22:09

Raphael Oliveira