12

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Andy Lebowitz
  • 1,471
  • 2
  • 16
  • 23
  • 3
    Why not set the text field's `autocapitalizationType` property to `Words`? Then as the user types, each word will automatically be capitalized. – rmaddy Jan 01 '16 at 17:59
  • 1
    @rmaddy why don't you post your comment as as answer? `textField.autocapitalizationType = .Words` – Leo Dabus Jan 01 '16 at 18:34
  • 1
    @LeoDabus Because my comment doesn't answer the question. It's just a quick comment to offer a possible alternate solution. I don't know if the OP actually has a different need. – rmaddy Jan 01 '16 at 18:46
  • try adding a target to your text field for the control events editing changed which calls a method where you can just do something like textField.text = textField.text?.capitalizedString – Leo Dabus Jan 01 '16 at 18:57

3 Answers3

19

Simply set Textfield's Capitalization for words.

enter image description here

technerd
  • 14,144
  • 10
  • 61
  • 92
8

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())
    
Idan
  • 5,405
  • 7
  • 35
  • 52
3

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
    }

}
Makalele
  • 7,431
  • 5
  • 54
  • 81