Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Is there a lesson on constricting a UITextField to positive numbers only ?

Any lesson on forcing a UITextField to accept only positive numbers? With a minimum and maximum ?

2 Answers

Richard thank you for your reply :) Do you know what delegate method would be the best to validate the minimum and maximum values of the UITextField ?

Hey Jose,

This delegate method should work:

func textFieldDidEndEditing(textField: UITextField) {
   if let text = textField.text, let number = Int(text)  {
       if number > someNumber {
          // do something    
       } else {
          // do something
       }
   }
}

Hey Jose,

From what I understand you want a UITextField to only accept numbers that are positive. I'm not sure if this is a way that you would want to go about it, but you can change the keyboard type to a numberpad like this

someTextField.keyboardType = UIKeyboardType.NumberPad

This would result in only accepting positive numbers.

keypad

If this isn't what you're looking for, I'd suggest searching for customized keyboards.

edit: As for having a maximum and minimum, I'd check the input in the textfieldDelegate method textFieldDidEndEditing:.

Good luck! :)