3

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?

Dima
  • 23,484
  • 6
  • 56
  • 83
Eliko
  • 851
  • 2
  • 7
  • 9
  • this is for disable copy/paste: http://stackoverflow.com/questions/6701019/how-to-disable-copy-paste-option-from-uitextfield-programmatically – Duyen-Hoa Apr 10 '15 at 16:39
  • @HoaParis This is in Objective-C, can you provide it in swift? – Eliko Apr 10 '15 at 16:54

3 Answers3

9

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.

Shamas S
  • 7,507
  • 10
  • 46
  • 58
  • I prefer for my code the textfield, but can you continue the code? I didn't get what I need to do after your code. – Eliko Apr 10 '15 at 16:55
  • This is the answer! great! do you know what i need to do if I got 2 text fields? – Eliko Apr 11 '15 at 11:39
  • Suppose you have 2 textFields, ageTextField and heightTextField. The first argument received in the function is of textField On top you put the check if (textField == ageTextField) and execute your code. – Shamas S Apr 11 '15 at 18:22
0

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.

Bhoomi Jagani
  • 2,413
  • 18
  • 24
0

To disable copy and paste:

func canPerformAction(_ action: Selector, withSender sender: AnyObject?) -> Bool
{
    if action == "paste:"
        {return false}
    return super.canPerformAction(action,withSender:sender)
}
mginn
  • 16,036
  • 4
  • 26
  • 54