0

I have 3 textFields called text1,text2, and text3.

How do I program them so that they only accept integer input?

Most of the similiar questions I've seen don't work in the newest version of XCode (using Swift 2) and don't cater to multiple textFields.

This one seemed helpful: How can I declare that a text field can only contain an integer?

Community
  • 1
  • 1
Thev
  • 1,105
  • 2
  • 13
  • 24

3 Answers3

1

First change the keyboardType to UIKeyboardTypeNumberPad as suggested by iAnurag

and also check the content change in the delegate method shouldChangeCharactersInRange (code tested with Swift 2.0 and Xcode 7)

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    // Find out what the text field will be after adding the current edit
    let text = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

    if  text == "" {
        return true
    }


    if let _ = Int(text) {
        return true
    } else {
     return false
    }

}
Community
  • 1
  • 1
Alaeddine
  • 6,104
  • 3
  • 28
  • 45
0

very simple and straight solution to this set Set the keyboardType property of the UITextField to UIKeyboardTypeDecimalPad. This won't allow your user to put alphabetics in the UITextField

Swift

self.promoTextField.keyboardType = UIKeyboardType.UIKeyboardTypeNumberPad

Objective C

myTextField.keyboardType = UIKeyboardTypeNumberPad;

OR

if you are using storyboard

enter image description here

iAnurag
  • 9,286
  • 3
  • 31
  • 48
0

Do what @iAnurag suggested but also implement a UITextFieldDelegate's - textField:shouldChangeCharactersInRange:replacementString: to check if the replacementString contains any non-digit characters. Because users can still copy text elsewhere and paste it on the text fields.

yusuke024
  • 2,189
  • 19
  • 12