Replace character while user is typing

Viewed 2301

Trying to replace a space with the character _

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.tag == 0 {
        username = textField.text!
        username = username.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
        textField.text! = username
    }
    return true
}

Trouble is, the space is replaced after the character following the space is typed.

4 Answers
Related