0

I have a UITextView that have a initial text of the initial price at $0.00. The user could set the price by entering number and when they do so, each character, starting from the right, will be replaced by the typed number. For example:

  • When typing 1, the text's changed to $0.01
  • Then typing 2, $0.12
  • Then 3, $1.23
  • Then 4, $12.34
  • Then backspace, $1.23
  • Another backspace, $0.12

Could you please show me how to setup that kind of input of UITextField in Swift? Thank you!

1 Answers1

1

Use UITextFieldDelete and implement something like this:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let text: NSString = (textField.text ?? "") as NSString
    let resultString = text.replacingCharacters(in: range, with: string)

    // Take the result string (user's text input) and format it how you wish...
    let formattedText = ...

    // Set the newly formatted string to the text fields's text property...
    textField.text = formattedText

    // Return false so the user's input is not applied to the text field (you're doing it on their behalf).
    return false
}
rosem
  • 1,311
  • 14
  • 19