I'm trying to capitalize the first letter of each word I put into a text field. I would like to put this code in here:
func textFieldShouldReturn(textField: UITextField) -> Bool {
//Here
}
My issue is that I have no idea what to put. I've tried creating a string like one post told me to do, and I'm having trouble:
nameOfString.replaceRange(nameOfString.startIndex...nameOfString.startIndex, with: String(nameOfString[nameOfString.startIndex]).capitalizedString)
I am not sure what to put inside that function to capitalize the first letter of each word.
This is forced capitalization of the first letter:
firstNameTextField.delegate = self
extension YourViewController : UITextFieldDelegate {
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let empty = textField.text?.isEmpty ?? true
if(empty) {
textField.text = string.uppercased()
return false
}
return true
}
}
From the code side of this question, assuming it's connected with IBOutlet
.
If the need is to change the text field behavior:
textField.autocapitalizationType = .Words
If the need is to change the input for the text field, i.e. the String
itself:
let newText = textField.text?.capitalizedString
Not asked in the question but yet: to Capitalize just the first letter:
let text = textField.text
let newText = String(text.characters.first!).capitalizedString + String(text.characters.dropFirst())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With