Uppercase characters in UItextfield
I have a question about iOS UIKeyboard
.
I have a UITextField
and I would to have the keyboard
with only uppercase characters.
I use a storyboard
and I tried to set the Cpitalization
as "All characters
" to UITextField properties
.
But this not solve my problem...any suggestion?
Solution 1:
Set your textfield type autocapitalizationType
to UITextAutocapitalizationTypeAllCharacters
on the UITextField
self.yourTexField.autocapitalizationType = UITextAutocapitalizationTypeAllCharacters;
After call delegate
// delegate method
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSRange lowercaseCharRange = [string rangeOfCharacterFromSet:[NSCharacterSet lowercaseLetterCharacterSet]];
if (lowercaseCharRange.location != NSNotFound) {
textField.text = [textField.text stringByReplacingCharactersInRange:range
withString:[string uppercaseString]];
return NO;
}
return YES;
}
Swift 5.4.2
self.yourTextField.autocapitalizationType = .allCharacters
Solution 2:
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
}
Solution 3:
For those looking for a Swift version.
Swift 4
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
textField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.uppercased())
return false
}
Original answer
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
textField.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string.uppercaseString)
return false
}
Using the Capitalization: All Characters
property just forces keyboard to open with caps lock on, but lets the user to turned it off.