user7987142
user7987142

Reputation:

Setting default UITextField value of 0 (Calculator)

I'm making an application and part of it has a sort of calculator functionality.

Users have 4 UITextFields to which they input numbers, all of which should be optional - but if they are left empty, it should act as if they have entered "0" into the field. How do I go about setting this default value of 0?

It's currently set so that the initial value in the UITextField is 0, but this can be deleted by the user (rendering an error), and doesn't allow for placeholder text.

Upvotes: 3

Views: 3339

Answers (1)

Rakesha Shastri
Rakesha Shastri

Reputation: 11242

You have set the default value of the textField to "0"

textField.text = "0"

Now you need to check if the user has changed the textField and if the change has resulted in an empty text field.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let textFieldString = textField.text, let range = Range(range, in: textFieldString) else {
        return false
    }
    let newString = textFieldString.replacingCharacters(in: range, with: string)
    if newString.isEmpty {
        textField.text = "0"
        return false
    } else if textField.text == "0" {
        textField.text = string
        return false
    }
    return true
}

Upvotes: 1

Related Questions