Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a max int value (not character count) to a UITextField

In Swift, is it possible to set a max INT value to a UITextField?

My use-case is I have 5 text fields that need to have a maximum int value. These values range from 500 all the way to 10,000. Each of the 5 different text fields will have a different max. I can't use a picker or dropdown because the increments will be 1. And a UISlider will be way too tough to "scrub in" on the number.

If the max int value is 5,000, user can not type in (on the keyboard type of number pad) a value any higher than 5000.

Character count won't work, because if the max value is 500, if I set to 3 characters, user can type in 999.

like image 753
Joe Avatar asked May 12 '16 19:05

Joe


People also ask

How do I limit the number of characters in UITextField?

If you have a UITextField or UITextView and want to stop users typing in more than a certain number of letters, you need to set yourself as the delegate for the control then implement either shouldChangeCharactersIn (for text fields) or shouldChangeTextIn (for text views).

How check textField is empty or not in Swift?

Basic Swift Code for iOS Apps Follow the below steps. Step 2 − Open Main. storyboard add one textField, one button and one label one below other as shown in the figure. On click of the button we will check whether the text field is empty or not and show the result in label.

What is textField delegate in Swift?

A set of optional methods to manage the editing and validation of text in a text field object.


1 Answers

You can check if the current value in the text field is less than the maximum integer value you've specified:

(You might want to change the keyboard type to .NumberPad at this point to let user type only numeric values.)

textField.keyboardType = .NumberPad

--

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
  let newText = NSString(string: textField.text!).stringByReplacingCharactersInRange(range, withString: string)
  if newText.isEmpty {
    return true
  }
  else if let intValue = Int(newText) where intValue <= self.maxValue {
    return true
  }
  return false
}

I created an example project for you. You can download and play around with it.

like image 192
Ozgur Vatansever Avatar answered Sep 30 '22 17:09

Ozgur Vatansever