DEV Community

Midhet Sulemani
Midhet Sulemani

Posted on

1 2

Realtime TextField updating

I just noticed while making a character count enabled textview that the count is always a few characters behind the actual text.

The problem in this was that the complete string that is entered isn’t updated in the text attributed of your text field until it returns true from the change characters in range function in its lifecycle.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let currentText = textField.text! + string
return true
}

The value of currentText in this function will give you the updated value or the complete string you’ve entered.

Update: The string gives you the latest character you have entered or deleted, if you want the updated text after each character is updated or deleted, your function will look something like this:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let char = string.cString(using: String.Encoding.utf8)!
let isBackSpace = strcmp(char, "\\b")
var currentText = ""
if (isBackSpace == -92) {
currentText = textField.text!.substring(to: textField.text!.index(before: textField.text!.endIndex))
}
else {
currentText = textField.text! + string
}
return true
}

This removes the backspaced string from your currentText as well as adds it if you have typed it in.

Hope this helped you :)

Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video 📹️

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay