How do I force a text field to be upper case only in Swift?

let textFieldOutput = "Wait a moment, please."
let newString = textFieldOutput.uppercased()
//The string is now "WAIT A MOMENT, PLEASE."

You can change the text to upper case with

string.uppercaseStringWithLocale(NSLocale.currentLocale())

You can use the method textField:shouldChangeCharactersInRange:replacementString: to change the text.


There are at least two options:

  1. Use the uppercaseString property of Swift's String class to generate an all-uppercase version of the text. This is a reasonable option if you want an upper case version of whatever is typed into the text field.

  2. Implement the method textField(_:shouldChangeCharactersInRange:replacementString:) in the text field's delegate. Your implementation should do the replacement itself using an upper case version of the replacement string, and then return false. This is the approach you want if it's important that the text appear upper case in the text field.


Step-1. In Main.Storyboard select the textfield and click on attribute inspectorenter image description here

Step-2. Then in text input traits -> select 'All Characters' in Capitalization.enter image description here

Tags:

Swift