Uppercase characters in UItextfield

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

    One issue I have with some of the above answers is if you try and set textfield.text, you will lose the cursor position. So if a user tries to edit the middle of the text, the cursor will jump to the end.

    Here is my Swift solution, still using UITextFieldDelegate:

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    
        if textField == textFieldToUppercase {
            if string == "" {
                // User presses backspace
                textField.deleteBackward()
            } else {
                // User presses a key or pastes
                textField.insertText(string.uppercaseString)
            }
            // Do not let specified text range to be changed
            return false
        }
    
        return true
    }
    

提交回复
热议问题