How to make textbox be uppercase only in Swift?

I want the text entry in the text box to be uppercase only.

Is there a way to limit the text box to only output uppercase letters, or even limit the software keyboard to display only uppercase letters for users?

+7
source share
8 answers
let textFieldOutput = "Wait a moment, please."
let newString = textFieldOutput.uppercased()
//The string is now "WAIT A MOMENT, PLEASE."
+10
source

Step 1. In Main.Storyboard, select the text box and click the attribute inspectorenter image description here

Step 2. Then in the text entry features → select "All characters" in the capitalization.enter image description here

+4
source

string.uppercaseStringWithLocale(NSLocale.currentLocale())

textField:shouldChangeCharactersInRange:replacementString:, .

+1

, :

var newString = myString.uppercaseString
+1

:

  • uppercaseString Swift String, - . , , .

  • textField(_:shouldChangeCharactersInRange:replacementString:) . , false. , , , .

+1

3:

var newString = myString.uppercased()
+1

Swift 4.2: .

Firstly. You can make the entered value from the keyboard (upperCase) in it programmatically.

yourTextField.text = yourString.uppercased()

Or a storyboard using the top keyboard.

StorBoard->TextInputTraits->Capitalization->Select ALL Characters

0
source

Changing the keyboard input type to All Charactersdoes not prevent the user from switching back to lowercase letters (at least in iOS 13). I use the following code (Swift 5.1) to use only new characters added to the text box with an uppercase letter instead of asking the full line again and again, as suggested in some other answers.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let firstLowercaseCharRange = string.rangeOfCharacter(from: NSCharacterSet.lowercaseLetters)
        if let _ = firstLowercaseCharRange {
            if let text = textField.text, text.isEmpty {
                textField.text = string.uppercased()
            }
            else {
                let beginning = textField.beginningOfDocument
                if let start = textField.position(from: beginning, offset: range.location),
                    let end = textField.position(from: start, offset: range.length),
                    let replaceRange = textField.textRange(from: start, to: end) {
                    textField.replace(replaceRange, withText: string.uppercased())
                }
            }
            return false
        }
        return true
    }
0
source

All Articles