How to limit number ranges in textfields

The code below limits the user to enter into the textfeld just numbers. What I am trying to do is limit the user to enter a number between -359 to 359. No letters just a number between that range.

    import UIKit

    class ViewController: UIViewController,UITextFieldDelegate {
 @IBOutlet var juju : UITextField!

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let aSet = NSCharacterSet(charactersIn:"0123456789").inverted
    let compSepByCharInSet = string.components(separatedBy: aSet)
    let numberFiltered = compSepByCharInSet.joined(separator: "")
    return string == numberFiltered
       }
     }

hi @timswift,
is there a question here?

cheers,

@timswift Thanks very much for your question, and my apologies for the delayed response.

To get a number within a range, you can do the following:

if -359…359 ~= String {

}

In your case however, you’re working with a String object. What you would do is cast the input String into an Int after you’ve established that the input String is indeed a number, and then check it’s within the range using some minor variation of the code above.

I hope this helps :slight_smile:

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.