Search code examples
iosiphoneipadswift

How to limit the numbers in the text field in Swift?


I want the user to fill in the textfield a number from 0 to 60. How can i limit the number chars to 2? How to limit the maximum number to 60? And how to cancel the 'paste' option on the textfield so the user won't be able to paste letters?


Solution

  • I think there are 2 ways you can do that.

    Implement the UITextFieldDelegate and implement function

    func textField(textField: UITextField,
        shouldChangeCharactersInRange range: NSRange,
        replacementString string: String) -> Bool {
    
        var startString = ""
    
        if textField.text != nil {
            startString += textField.text!
        }
    
        startString += string
    
        var limitNumber = startString.toInt()
    
        if limitNumber > 60 {
            return false
        } else {
            return true
        }
    }
    

    In this Each time check what has been entered to the UITextField so far, convert to Integer and if the new value is higher than 60, return false. (Also show the appropriate error to the user).

    I think a much better way would be to provide UIPickerView.