Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to capitalize the first letter of each word in a text field Using Swift

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.

like image 540
Andy Lebowitz Avatar asked Jan 01 '16 17:01

Andy Lebowitz


2 Answers

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
    }

}
like image 109
Makalele Avatar answered Oct 04 '22 20:10

Makalele


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())
    
like image 41
Idan Avatar answered Oct 04 '22 21:10

Idan