Uppercase characters in UItextfield

前端 未结 17 1273
萌比男神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:14

    Finally I found the way that respects also editing text in the middle of the string in UITextField.

    The problem is that if you replace whole text by UITextFiled.text property the actual cursor moves to end of text. So you need to use .replace() method to specify exactly which characters you want to update to upperCase.

    Last thing is to return string.isEmpty as return value of function - otherwise you are not allowing deleting of text.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if let text = textField.text, let textRange = Range(range, in: text) {
            let uppercasedString = string.uppercased()
            let updatedText = text.replacingCharacters(in: textRange, with: uppercasedString)
            if let selectedTextRange = textField.selectedTextRange {
                textField.replace(selectedTextRange, withText: uppercasedString)
                approveButtonState(vin: updatedText)
            }
            return string.isEmpty
        }
        return false
    }
    

提交回复
热议问题