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.
The method textField(_, shouldChangeCharactersIn:, replacementString:) is a query, you should not be putting side effects there. Instead make an IBAction and attach it to the editingChanged UIControlEvent...
@IBAction func editingChanged(_ sender: UITextField) {
sender.text = sender.text?.replacingOccurrences(of: " ", with: "_")
}
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