0

I have 5 text fields in the ViewController that I'd like to automatically be set to number "0" after deleting written numbers.

It's default set to "0" before entering numbers from the storyboard (which is correct). But after deleting written numbers, the text field is empty. I would like it to automatically be set to "0" when empty again. And not just the placeholder, but actual number.

Before entering numbers

When entering numbers

After entering numbers

filiwonka
  • 1
  • 2
  • Do you want to set 0 to textfield when it is empty? – Dilan Apr 13 '20 at 13:23
  • Take a look at https://developer.apple.com/documentation/uikit/uitextfielddelegate/1619599-textfield – Ratul Sharker Apr 13 '20 at 13:33
  • Yes. It is default set to "0" before entering numbers from the storyboard (which is correct). But after deleting written numbers, the text field is empty. I would like it to automatically be reset to "0", when empty again. – filiwonka Apr 13 '20 at 13:35
  • You should create a custom text field to allow digits only https://stackoverflow.com/a/34294660/2303865 – Leo Dabus Apr 13 '20 at 15:46
  • Note that setting the keyboard to numeric it is not enough to avoid the user to paste regular text to the text field – Leo Dabus Apr 13 '20 at 15:48

1 Answers1

3

Make the view controller be the delegate of the text field, and implement the following methods:

extension ViewController: UITextFieldDelegate {
    func textFieldDidChangeSelection(_ textField: UITextField) {
        if textField.text?.isEmpty == true {
            textField.text = "0"
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField.text?.isEmpty == true && string.isEmpty {
            textField.text = "0"
            return false
        } else if textField.text == "0" {
            textField.text = string
            return false
        }
        return true
    }
}

If the user deletes a text entirely, the text field will show "0". If the user starts typing with the initial "0" value, the "0" will disappear and show the user-typed text.

Edit: To set a view controller a delegate of the text field, right click (or ctrl + click) and drag from the textfield to the view controller in the storyboard:

storyboard

and choose delegate:

delegate

If you are not using a storyboard or don't want to use it, you can always do it programmatically.

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self
    }
Jay Lee
  • 1,684
  • 1
  • 15
  • 27