Andy Lebowitz
Andy Lebowitz

Reputation: 1511

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.

Upvotes: 12

Views: 11460

Answers (3)

Makalele
Makalele

Reputation: 7551

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
    }

}

Upvotes: 3

Idan
Idan

Reputation: 5450

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())
    

Upvotes: 8

technerd
technerd

Reputation: 14514

Simply set Textfield's Capitalization for words.

enter image description here

Upvotes: 19

Related Questions