Uppercase characters in UItextfield

前端 未结 17 1215
萌比男神i
萌比男神i 2020-12-24 04:34

I have a question about iOS UIKeyboard.

I have a UITextField and I would to have the keyboard with only uppercase characters.<

17条回答
  •  攒了一身酷
    2020-12-24 05:18

    Maybe it's a bit late for an answer here, but as I have a working solution someone might find it useful.

    Well, in the following textfield delegate method, check if the new string contains any lowercase characters. If so, then:

    • Append the character that was just typed to the textfield's text.
    • Make all the textfield's text uppercased.
    • Make sure that false is returned by the method.

    Otherwise just return true and let the method work as expected.

    Here's its implementation:

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        var returnValue = true
        let lowercaseRange = string.rangeOfCharacter(from: CharacterSet.lowercaseLetters)
        if let _ = lowercaseRange?.isEmpty {
            returnValue = false
        }
    
        if !returnValue {
            textField.text = (textField.text! + string).uppercased()
        }
    
        return returnValue
    }
    

    The above has worked perfectly for me, and a similar implementation works for textviews too, after making the proper adjustments first of course.

    Hope it helps!

提交回复
热议问题