How to force to type always lowercase or uppercase for some textfields in swift language?
Asked
Active
Viewed 1.1k times
3

fatihyildizhan
- 8,614
- 7
- 64
- 88
-
5possible duplicate of [iPhone Force Textbox Input to Upper Case](http://stackoverflow.com/questions/2027164/iphone-force-textbox-input-to-upper-case) – Shamas S Aug 13 '15 at 13:05
-
This solution if for swift language. Not for Objective-C. – fatihyildizhan Aug 13 '15 at 13:08
-
accepted answer can be used in swift without troubles – SwiftStudier Aug 13 '15 at 16:00
-
2this is valid question and i don't understand why this is down voted. It can be marked duplicate if its already asked. – Stephen May 24 '16 at 05:26
2 Answers
10
You should return false
in if block
because you already updated the textfield.
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if textField.isEqual(textFieldBodrum) {
textFieldBodrum.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string.lowercaseString)
return false
} else if textField.isEqual(textFieldYalikavak) {
textFieldYalikavak.text = (textField.text as NSString).stringByReplacingCharactersInRange(range, withString: string.uppercaseString)
return false
}
return true
}
If you don't want to affect other textfields you should return true
end of the shouldChangeCharactersInRange function
.
https://gist.github.com/fatihyildizhan/ac5f476aebd306b0580a1fa069f153a3

fatihyildizhan
- 8,614
- 7
- 64
- 88
-
Swift 4.2 the method has been changed to: yourTextField.text = (textField.text! as NSString).replacingCharacters(in: range, with: string.lowercased()) – Lance Samaria Feb 28 '19 at 12:25
-
1The accepted answer worked but caused the unforeseen problem of the target method I added to .editingChanged not firing. The answer was to change anything uppercase to lowercase in a separate .editingChanged method. Look at @LeoDabus' answer here stackoverflow.com/a/54926833/4833705 – Lance Samaria Feb 28 '19 at 14:14
8
The simplest solution is to set the text field's autocapitalizationType
property to .None
to default to lowercase input or .AllCharacters
to default to uppercase input. The user can still use the shift key to change capitalization though.

hennes
- 9,147
- 4
- 43
- 63
-
1You are right but I want to FORCE to typing lowercase or uppercase. – fatihyildizhan Aug 13 '15 at 13:23