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:
Use the
uppercaseString
property of Swift'sString
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.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 returnfalse
. 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 inspector
Step-2. Then in text input traits -> select 'All Characters' in Capitalization.