jenny sam
jenny sam

Reputation: 191

How do i limit the text field for hour and second?

Suppose i have a text field that takes minute and hour as input. Now how can i limit the text field for hour upto only 24 and minutes field to 60.

Upvotes: 0

Views: 547

Answers (2)

David Pasztor
David Pasztor

Reputation: 54745

Make your ViewController class conform to the UITextFieldDelegate protocol, set minuteField.delegate = self and hourField.delegate = self, then implement the shouldChangeCharactersIn range function and check that the input is numeric and that the number of characters <= 2. You can use didEndEditing to check that the number is in your expected range.

extension VC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        if textField == minuteField {
            guard let minuteText = textField.text, let minutes = Int(minuteText) else {return}
            if minutes < 0 || minutes > 60 {
                textField.text = ""
            }
        } else if textField == hourField {
            guard let hourText = textField.text, let hours = Int(hourText) else { return }
            if hours < 0 || hours > 24 {
                textField.text = ""
            }
        }
    }

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if string.isEmpty {
            return true
        } else if string.rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) != nil {
            return false
        } else if let numberOfChars = textField.text?.characters.count, numberOfChars >= 2 {
            return false
        } else {
            return true
        }
    }
}

Upvotes: 0

danh
danh

Reputation: 62676

A text field's contents can be controlled via its delegate methods, including one that asks if it shouldChangeCharacters. If user types something out of bounds, it can be corrected then, or even disallowed by returning false.

But a good UI practice is to not let user make an error to begin with. That's the reason for pickers.

Upvotes: 1

Related Questions