Reputation: 2773
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
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
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
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
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