How to allow only certain set of numbers in a UITextfield in swift 2.0

I am having a UITextField in which i get the month number as input. I am successful in limiting the no of characters to 2 in the UITextField. But i want users to enter only the values from 1 to 12 and none other than that. This has to be done simultaneously when the user types the numbers i.e in func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool. If i use a simple if condition to check the each character and return false in else part the textfield won't allow me to use clear or retype any other character. someone help me.

Set keyboard type as Number Pad

add this

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

    if let text = textField.text {

        let newStr = (text as NSString)
            .stringByReplacingCharactersInRange(range, withString: string)
        if newStr.isEmpty {
            return true
        }
        let intvalue = Int(newStr)
        return (intvalue >= 0 && intvalue <= 12)
    }
    return true
}

How to allow only certain set of numbers in a UITextfield in swift 2.0 , vote 13 Down vote. Swift 2.0. For only allowing numbers and one "." decimal in uitextfield. Make sure to set the delegate property of the appropriate text field. Method 1: Changing the Text Field Type from storyboard. Select the text field that you want to restrict to numeric input. Go to its attribute inspector. Select the keyboard type and choose number pad from there.

You can do it simultaneously by checking the TextField value inside shouldChangeCharactersInRange.

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let inputStr = textField.text?.stringByAppendingString(string)
    let inputInt = Int(inputStr!)
    if inputInt > 0 && inputInt < 13 {
        return true
    } else {
        return false
    }
}

How to restrict UITextField to take only numbers in Swift?, Check out this to set Limit the numbers and allow only numbers 0 to 9. func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,� Allow only custom characters If you want that your UITextField should accept only characters which you wants, then just write one line of code in your viewDidLoad function which is below self.textField.allowedCharInString = "1234abcde"

=> you can Define limite of char like this:-

#define NUMBERS_ONLY @"1234567890"

#define  CHARACTER_LIMIT 2

=> and based on define limit char you can use and try it below method :-

  - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string  
    {

        NSUInteger newLength = [textField.text length] + [string length] - range.length;

        NSCharacterSet *cs = [[NSCharacterSet characterSetWithCharactersInString:NUMBERS_ONLY] invertedSet];

        NSString *filtered = [[string componentsSeparatedByCharactersInSet:cs] componentsJoinedByString:@""];

        return (([string isEqualToString:filtered])&&(newLength <= CHARACTER_LIMIT));

    }

Swift 3, Do you often forget your daily tasks? Try out my To-do List Reminder app to manage your routines Duration: 2:52 Posted: Dec 28, 2016 In this video, we will learn how to restrict user to allow only numbers to be inputed in UITextField or only numbers to be acceptable by UITextField. You can change the acceptable characters to

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

        // Create an `NSCharacterSet` set which includes everything *but* the digits
        let inverseSet = NSCharacterSet(charactersInString:"0123456789").invertedSet

        // At every character in this "inverseSet" contained in the string,
        // split the string up into components which exclude the characters
        // in this inverse set
        let components = string.componentsSeparatedByCharactersInSet(inverseSet)

        // Rejoin these components
        let filtered = components.joinWithSeparator("")  // use join("", components) if you are using Swift 1.2

        // If the original string is equal to the filtered string, i.e. if no
        // inverse characters were present to be eliminated, the input is valid
        // and the statement returns true; else it returns false
        return string == filtered

}

see this link-- Limit UITextField input to numbers in Swift

UITextField, iOS 2.0+; Mac Catalyst 13.0+; tvOS 9.0+ Usually, you dismiss the keyboard in response to specific interactions. keyboards for entering numbers, URLs, email addresses, and other specific types of To set this attribute programmatically, use the font property. This option is available only when formatting plain strings . Only allow certain characters (or don’t allow certain characters) Save the text and show it again when they relaunch the app Let the user stop editing by tapping the return button on the keyboard We’ll wrap up by talking about some of the display and behavior options built in to UITextField.

Check out this to set Limit the numbers and allow only numbers 0 to 9.

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField == mobileNumber {
        let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
        let compSepByCharInSet = string.components(separatedBy: aSet)
        let numberFiltered = compSepByCharInSet.joined(separator: "")
        let length = (mobileNumber.text?.count)! + string.count - range.length
        return string == numberFiltered && length <= LIMIT
    }else if textField == userType {
        return false
    }
    return true
}

UITextfield limit with no special charecters ios objective c, Restrict the number of Set the maximum character length of a UITextField 37 answers certain number of letters, you Swift, the Swift logo, Swift Playgrounds, Xcode, In Swift 2.0 this has to be done as. let chars = Set("abcde".characters) The� To set this attribute programatically, use the border Style property. Clear Button. The behavior of the clear button. The clear button is a built-in overlay view that the user taps to delete all of the text in a text field. Use this attribute to define when the clear button appears. To set this attribute programatically, use theclear Button

Swift 4 UITextField max length in Alert, Set limit to UITextField in ObjectiveC, You can always make use textField want to stop users typing in more than a certain number of letters, you need to set yourself as the How to restrict UITextField to take only numbers in Swift?, Swift 2.0. How to program an iOS text field that takes only numeric input or specific characters with a maximum… One of the most popular tutorials on this blog, this covers a way to constraint text fields so that they accept only numeric input or specific characters, and limits the number of characters they will accept.

How to restrict UITextField to take only numbers in Swift?, Is there any way to restrict user to enter only numeric values in a UITextField ? delegate method to accept Duration: 2:52 Posted: Dec 28, 2016 Swift 2.0. to consider only two files: The view controller, ViewController.swift, and; a set of Take in more than a certain I've specified 16 as the maximum number of characters,� Use that method to allow or prevent the editing of the text field’s contents. The text field becomes the first responder. In response, the system displays the keyboard (or the text field’s input view) and posts the keyboard Will Show Notification and keyboard Did Show Notification notifications as needed.

Skyscanner/SkyFloatingLabelTextField: A beautiful and , Written in Swift. (error, selected, highlighted states), and is very much customizable and extensible. From version 2.0 onwards only compatible with Swift 3. To customize the colors of the textfield, set a few properties - either from code, or from The control was designed to allow further customization in subclasses. There should be some user input in a way that the user inputs some numbers and the program uses the different numbers to calculate an output. As far as I have seen into the iPhone SDK there seems to be only the UITextField for the input, but you only get NSString back.

Comments
  • thanks this works great with my codevar length = (count(textField.text) + count(string) - range.length) and returned as return length < 3 && (intvalue > 0 && intvalue <= 12) ? true : false
  • ? true : false is redundant return 1...12 ~= intvalue
  • If the else part is executed and false is returned you cannot clear the text or reenter the text.
  • i'm not sure about your code, but i have checked it, the code above didn't do anything to neither block the user clear the text nor re enter text.
  • sorry my mistake. your code too works good and is very simple
  • this objective c code is nothing different than the swift answer above. it is just the objective c version with character limit . var length = (count(textField.text) + count(string) - range.length) and return length < 3 this is the swift 1.2 for simple length constrain
  • add if condition in this function to check value of textfield is less then equal to 12 and greater than equal to 1.
  • I already tried this code it allows 13 to 99 too. also if i use if condition and return false i can no longer edit the text field even backspace.