Limit UITextField input to numbers in Swift












4















How can I get limit the user's TextField input to numbers in Swift?










share|improve this question




















  • 3





    Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

    – Chris
    Nov 30 '14 at 16:42











  • also useful stackoverflow.com/a/26337774/294884

    – Fattie
    Sep 28 '15 at 0:38
















4















How can I get limit the user's TextField input to numbers in Swift?










share|improve this question




















  • 3





    Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

    – Chris
    Nov 30 '14 at 16:42











  • also useful stackoverflow.com/a/26337774/294884

    – Fattie
    Sep 28 '15 at 0:38














4












4








4


6






How can I get limit the user's TextField input to numbers in Swift?










share|improve this question
















How can I get limit the user's TextField input to numbers in Swift?







ios swift uitextfield






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 30 '14 at 17:48









Lyndsey Scott

29.6k671113




29.6k671113










asked Nov 30 '14 at 16:34









SantisSantis

40115




40115








  • 3





    Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

    – Chris
    Nov 30 '14 at 16:42











  • also useful stackoverflow.com/a/26337774/294884

    – Fattie
    Sep 28 '15 at 0:38














  • 3





    Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

    – Chris
    Nov 30 '14 at 16:42











  • also useful stackoverflow.com/a/26337774/294884

    – Fattie
    Sep 28 '15 at 0:38








3




3





Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

– Chris
Nov 30 '14 at 16:42





Are you using storyboards? If you are there is an option in the property inspector to only allow numeric characters

– Chris
Nov 30 '14 at 16:42













also useful stackoverflow.com/a/26337774/294884

– Fattie
Sep 28 '15 at 0:38





also useful stackoverflow.com/a/26337774/294884

– Fattie
Sep 28 '15 at 0:38












4 Answers
4






active

oldest

votes


















34














You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:



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
}




Updated for Swift 3:



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

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

// 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.components(separatedBy: inverseSet)

// Rejoin these components
let filtered = components.joined(separator: "") // 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
}





share|improve this answer





















  • 1





    join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

    – Rao
    Sep 17 '15 at 16:29






  • 4





    pretty code. this is a model of how to write self-documenting code. and dat's the only code.

    – Fattie
    Sep 28 '15 at 0:36






  • 1





    let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

    – JAck
    Oct 17 '16 at 11:05













  • and what to do with those functions?

    – user924
    Apr 12 '18 at 12:01











  • why you didn't mention UITextFieldDelegate??

    – user924
    Apr 12 '18 at 12:02



















1















1st you have to inherit the UITextViewDelegate class with you own
class




class ViewController: UIViewController, UITextViewDelegate {



2nd add an IBOutlet




@IBOutlet weak var firstName: UITextField!



3rd you have to assure this object is using




override func viewDidLoad() {
super.viewDidLoad()
firstName.delegate = self
}


func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
if textField == firstName {
let allowedCharacters = "1234567890"
let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
let typedCharacterSet = CharacterSet(charactersIn: string)
let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
let Range = range.length + range.location > (fnameTF.text?.count)!

if Range == false && alphabet == false {
return false
}


let NewLength = (fnameTF.text?.count)! + string.count - range.length
return NewLength <= 10


}
}





share|improve this answer































    0














    Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,



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


    You need to implement the following method and intercept the entered character and either through the following regular expression



    "^([0-9]+)?(\.([0-9]{1,2})?)?$"


    or



    [NSCharacterSet decimalDigitCharacterSet]


    you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.






    share|improve this answer































      0














      In swift 4.1 and Xcode 10



      Add UITextFieldDelegate to your class



      class YourViewController: UIViewController, UITextFieldDelegate


      Then write this code in your viewDidLoad()



      yourTF.delegate = self


      Write this textfield delegate function



      //MARK - UITextField Delegates
      func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
      //For numers
      if textField == yourTF {
      let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
      let characterSet = CharacterSet(charactersIn: string)
      return allowedCharacters.isSuperset(of: characterSet)
      }
      return true
      }





      share|improve this answer























        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        autoActivateHeartbeat: false,
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27215495%2flimit-uitextfield-input-to-numbers-in-swift%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes









        34














        You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:



        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
        }




        Updated for Swift 3:



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

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

        // 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.components(separatedBy: inverseSet)

        // Rejoin these components
        let filtered = components.joined(separator: "") // 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
        }





        share|improve this answer





















        • 1





          join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

          – Rao
          Sep 17 '15 at 16:29






        • 4





          pretty code. this is a model of how to write self-documenting code. and dat's the only code.

          – Fattie
          Sep 28 '15 at 0:36






        • 1





          let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

          – JAck
          Oct 17 '16 at 11:05













        • and what to do with those functions?

          – user924
          Apr 12 '18 at 12:01











        • why you didn't mention UITextFieldDelegate??

          – user924
          Apr 12 '18 at 12:02
















        34














        You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:



        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
        }




        Updated for Swift 3:



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

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

        // 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.components(separatedBy: inverseSet)

        // Rejoin these components
        let filtered = components.joined(separator: "") // 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
        }





        share|improve this answer





















        • 1





          join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

          – Rao
          Sep 17 '15 at 16:29






        • 4





          pretty code. this is a model of how to write self-documenting code. and dat's the only code.

          – Fattie
          Sep 28 '15 at 0:36






        • 1





          let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

          – JAck
          Oct 17 '16 at 11:05













        • and what to do with those functions?

          – user924
          Apr 12 '18 at 12:01











        • why you didn't mention UITextFieldDelegate??

          – user924
          Apr 12 '18 at 12:02














        34












        34








        34







        You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:



        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
        }




        Updated for Swift 3:



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

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

        // 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.components(separatedBy: inverseSet)

        // Rejoin these components
        let filtered = components.joined(separator: "") // 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
        }





        share|improve this answer















        You can use UITextFieldDelegate’s shouldChangeCharactersInRange method to limit the user's input to numbers:



        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
        }




        Updated for Swift 3:



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

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

        // 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.components(separatedBy: inverseSet)

        // Rejoin these components
        let filtered = components.joined(separator: "") // 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
        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Apr 15 '18 at 18:17

























        answered Nov 30 '14 at 17:39









        Lyndsey ScottLyndsey Scott

        29.6k671113




        29.6k671113








        • 1





          join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

          – Rao
          Sep 17 '15 at 16:29






        • 4





          pretty code. this is a model of how to write self-documenting code. and dat's the only code.

          – Fattie
          Sep 28 '15 at 0:36






        • 1





          let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

          – JAck
          Oct 17 '16 at 11:05













        • and what to do with those functions?

          – user924
          Apr 12 '18 at 12:01











        • why you didn't mention UITextFieldDelegate??

          – user924
          Apr 12 '18 at 12:02














        • 1





          join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

          – Rao
          Sep 17 '15 at 16:29






        • 4





          pretty code. this is a model of how to write self-documenting code. and dat's the only code.

          – Fattie
          Sep 28 '15 at 0:36






        • 1





          let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

          – JAck
          Oct 17 '16 at 11:05













        • and what to do with those functions?

          – user924
          Apr 12 '18 at 12:01











        • why you didn't mention UITextFieldDelegate??

          – user924
          Apr 12 '18 at 12:02








        1




        1





        join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

        – Rao
        Sep 17 '15 at 16:29





        join("", components) breaks in Swift 2.0, do components.joinWithSeparator("") instead.

        – Rao
        Sep 17 '15 at 16:29




        4




        4





        pretty code. this is a model of how to write self-documenting code. and dat's the only code.

        – Fattie
        Sep 28 '15 at 0:36





        pretty code. this is a model of how to write self-documenting code. and dat's the only code.

        – Fattie
        Sep 28 '15 at 0:36




        1




        1





        let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

        – JAck
        Oct 17 '16 at 11:05







        let components = string.components(separatedBy: inverseSet) // Rejoin these components let filtered = components.joined(separator: "") for Swift 3

        – JAck
        Oct 17 '16 at 11:05















        and what to do with those functions?

        – user924
        Apr 12 '18 at 12:01





        and what to do with those functions?

        – user924
        Apr 12 '18 at 12:01













        why you didn't mention UITextFieldDelegate??

        – user924
        Apr 12 '18 at 12:02





        why you didn't mention UITextFieldDelegate??

        – user924
        Apr 12 '18 at 12:02













        1















        1st you have to inherit the UITextViewDelegate class with you own
        class




        class ViewController: UIViewController, UITextViewDelegate {



        2nd add an IBOutlet




        @IBOutlet weak var firstName: UITextField!



        3rd you have to assure this object is using




        override func viewDidLoad() {
        super.viewDidLoad()
        firstName.delegate = self
        }


        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if textField == firstName {
        let allowedCharacters = "1234567890"
        let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
        let typedCharacterSet = CharacterSet(charactersIn: string)
        let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
        let Range = range.length + range.location > (fnameTF.text?.count)!

        if Range == false && alphabet == false {
        return false
        }


        let NewLength = (fnameTF.text?.count)! + string.count - range.length
        return NewLength <= 10


        }
        }





        share|improve this answer




























          1















          1st you have to inherit the UITextViewDelegate class with you own
          class




          class ViewController: UIViewController, UITextViewDelegate {



          2nd add an IBOutlet




          @IBOutlet weak var firstName: UITextField!



          3rd you have to assure this object is using




          override func viewDidLoad() {
          super.viewDidLoad()
          firstName.delegate = self
          }


          func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
          if textField == firstName {
          let allowedCharacters = "1234567890"
          let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
          let typedCharacterSet = CharacterSet(charactersIn: string)
          let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
          let Range = range.length + range.location > (fnameTF.text?.count)!

          if Range == false && alphabet == false {
          return false
          }


          let NewLength = (fnameTF.text?.count)! + string.count - range.length
          return NewLength <= 10


          }
          }





          share|improve this answer


























            1












            1








            1








            1st you have to inherit the UITextViewDelegate class with you own
            class




            class ViewController: UIViewController, UITextViewDelegate {



            2nd add an IBOutlet




            @IBOutlet weak var firstName: UITextField!



            3rd you have to assure this object is using




            override func viewDidLoad() {
            super.viewDidLoad()
            firstName.delegate = self
            }


            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if textField == firstName {
            let allowedCharacters = "1234567890"
            let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
            let typedCharacterSet = CharacterSet(charactersIn: string)
            let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
            let Range = range.length + range.location > (fnameTF.text?.count)!

            if Range == false && alphabet == false {
            return false
            }


            let NewLength = (fnameTF.text?.count)! + string.count - range.length
            return NewLength <= 10


            }
            }





            share|improve this answer














            1st you have to inherit the UITextViewDelegate class with you own
            class




            class ViewController: UIViewController, UITextViewDelegate {



            2nd add an IBOutlet




            @IBOutlet weak var firstName: UITextField!



            3rd you have to assure this object is using




            override func viewDidLoad() {
            super.viewDidLoad()
            firstName.delegate = self
            }


            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            if textField == firstName {
            let allowedCharacters = "1234567890"
            let allowedCharacterSet = CharacterSet(charactersIn: allowedCharacters)
            let typedCharacterSet = CharacterSet(charactersIn: string)
            let alphabet = allowedCharacterSet.isSuperset(of: typedCharacterSet)
            let Range = range.length + range.location > (fnameTF.text?.count)!

            if Range == false && alphabet == false {
            return false
            }


            let NewLength = (fnameTF.text?.count)! + string.count - range.length
            return NewLength <= 10


            }
            }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Oct 11 '18 at 7:26









            akbar khanakbar khan

            313110




            313110























                0














                Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,



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


                You need to implement the following method and intercept the entered character and either through the following regular expression



                "^([0-9]+)?(\.([0-9]{1,2})?)?$"


                or



                [NSCharacterSet decimalDigitCharacterSet]


                you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.






                share|improve this answer




























                  0














                  Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,



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


                  You need to implement the following method and intercept the entered character and either through the following regular expression



                  "^([0-9]+)?(\.([0-9]{1,2})?)?$"


                  or



                  [NSCharacterSet decimalDigitCharacterSet]


                  you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.






                  share|improve this answer


























                    0












                    0








                    0







                    Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,



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


                    You need to implement the following method and intercept the entered character and either through the following regular expression



                    "^([0-9]+)?(\.([0-9]{1,2})?)?$"


                    or



                    [NSCharacterSet decimalDigitCharacterSet]


                    you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.






                    share|improve this answer













                    Well the iOS provides no such functionality where you can specify textfield to accept only numeric characters. The only way through would be, one of UITextFieldDelegate methods, which is as follows,



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


                    You need to implement the following method and intercept the entered character and either through the following regular expression



                    "^([0-9]+)?(\.([0-9]{1,2})?)?$"


                    or



                    [NSCharacterSet decimalDigitCharacterSet]


                    you can find out whether the entered character is numeric and return YES if it matches the regular expression or character set else return NO.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Nov 30 '14 at 17:03









                    ldinduldindu

                    2,47411120




                    2,47411120























                        0














                        In swift 4.1 and Xcode 10



                        Add UITextFieldDelegate to your class



                        class YourViewController: UIViewController, UITextFieldDelegate


                        Then write this code in your viewDidLoad()



                        yourTF.delegate = self


                        Write this textfield delegate function



                        //MARK - UITextField Delegates
                        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                        //For numers
                        if textField == yourTF {
                        let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
                        let characterSet = CharacterSet(charactersIn: string)
                        return allowedCharacters.isSuperset(of: characterSet)
                        }
                        return true
                        }





                        share|improve this answer




























                          0














                          In swift 4.1 and Xcode 10



                          Add UITextFieldDelegate to your class



                          class YourViewController: UIViewController, UITextFieldDelegate


                          Then write this code in your viewDidLoad()



                          yourTF.delegate = self


                          Write this textfield delegate function



                          //MARK - UITextField Delegates
                          func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                          //For numers
                          if textField == yourTF {
                          let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
                          let characterSet = CharacterSet(charactersIn: string)
                          return allowedCharacters.isSuperset(of: characterSet)
                          }
                          return true
                          }





                          share|improve this answer


























                            0












                            0








                            0







                            In swift 4.1 and Xcode 10



                            Add UITextFieldDelegate to your class



                            class YourViewController: UIViewController, UITextFieldDelegate


                            Then write this code in your viewDidLoad()



                            yourTF.delegate = self


                            Write this textfield delegate function



                            //MARK - UITextField Delegates
                            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                            //For numers
                            if textField == yourTF {
                            let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
                            let characterSet = CharacterSet(charactersIn: string)
                            return allowedCharacters.isSuperset(of: characterSet)
                            }
                            return true
                            }





                            share|improve this answer













                            In swift 4.1 and Xcode 10



                            Add UITextFieldDelegate to your class



                            class YourViewController: UIViewController, UITextFieldDelegate


                            Then write this code in your viewDidLoad()



                            yourTF.delegate = self


                            Write this textfield delegate function



                            //MARK - UITextField Delegates
                            func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
                            //For numers
                            if textField == yourTF {
                            let allowedCharacters = CharacterSet(charactersIn:"0123456789")//Here change this characters based on your requirement
                            let characterSet = CharacterSet(charactersIn: string)
                            return allowedCharacters.isSuperset(of: characterSet)
                            }
                            return true
                            }






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Jan 20 at 6:19









                            iOSiOS

                            2,37711942




                            2,37711942






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27215495%2flimit-uitextfield-input-to-numbers-in-swift%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                Callistus III

                                Ostreoida

                                Plistias Cous