luke
luke

Reputation: 2773

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.

Upvotes: 3

Views: 2935

Answers (4)

Damyan Todorov
Damyan Todorov

Reputation: 566

Try this code and you will get the main idea

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

    var text = textField.text! + string

    if (text.range(of: " ") != nil) {
        text = text.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
        textField.text! = text
        return false
    }

    return true
}

Upvotes: 0

Grumme
Grumme

Reputation: 806

You could try using this extension for String

extension String {
    func removingWhitespaces() -> String {
        return components(separatedBy: .whitespaces).joined()
    }
}

Using:

if textField.tag == 0 {
    username = textField.text!
    username = username.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
    username.removingWhitespaces()
    textField.text! = username
}
return true

Upvotes: 0

Utihnuli Svitac
Utihnuli Svitac

Reputation: 11

You need to make logic in key down , key up event ... To ask in key down event is key_code=='ENTER'(i think its 13 code) , and if it is write in input _ and return false , to break the event and do the job right... I had made similar things with javascript

Upvotes: 0

Daniel T.
Daniel T.

Reputation: 33967

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: "_")
}

Upvotes: 7

Related Questions