Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace character while user is typing

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.

like image 770
luke Avatar asked Aug 11 '26 04:08

luke


1 Answers

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: "_")
}
like image 171
Daniel T. Avatar answered Aug 13 '26 00:08

Daniel T.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!