Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

swift

I would like the text entry on a text field to be upper case only.

Is there a way to limit the text field to output only upper case letters or even limit the software keyboard to only display upper case letters to users?

like image 417
Fiducial13 Avatar asked Nov 25 '14 15:11

Fiducial13


People also ask

How do I make text capital in Swift?

To convert a String to Uppercase in Swift, use String. uppercased() function. Call uppercased() function on the String. The function returns a new string with the contents of the original string transformed to uppercase alphabets.

How do you capitalize text in SwiftUI?

SwiftUI's TextField view normally lets users write their text in whatever case they want, but if you want to control that you can force either uppercase or lowercase text using the textCase() modifier. Important: If you're using Xcode 12 you need to use RoundedBorderTextFieldStyle() rather than .

How do you make a text field non editable in Swift?

How do you make a text field Uneditable in Swift? Within code: textfield. enable = false.


4 Answers

let textFieldOutput = "Wait a moment, please."
let newString = textFieldOutput.uppercased()
//The string is now "WAIT A MOMENT, PLEASE."
like image 124
Justin Vallely Avatar answered Sep 17 '22 15:09

Justin Vallely


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

like image 35
Raghib Arshi Avatar answered Sep 17 '22 15:09

Raghib Arshi


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.

like image 26
dasdom Avatar answered Sep 21 '22 15:09

dasdom


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.

like image 43
Caleb Avatar answered Sep 17 '22 15:09

Caleb