Eliko
Eliko

Reputation: 881

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?

Upvotes: 3

Views: 10715

Answers (3)

Shamas S
Shamas S

Reputation: 7549

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.

Upvotes: 10

mginn
mginn

Reputation: 16114

To disable copy and paste:

func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool
{
    if action == "paste:"
        {return false}
    return super.canPerformAction(action,withSender:sender)
}

Upvotes: 0

Bhoomi Jagani
Bhoomi Jagani

Reputation: 2423

Use textfield's delegate method

Where 10 is Max limit for text field...

      func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
        let newLength = countElements(textField.text) + countElements(string) - range.length
       return newLength <= 10 // Bool
 }

If countElements not work in latest version of s wift use count instead of countElements.

Upvotes: 0

Related Questions