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

后端 未结 2 830
故里飘歌
故里飘歌 2021-01-13 05:20

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

相关标签:
2条回答
  • 2021-01-13 05:45

    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.

    0 讨论(0)
  • 2021-01-13 05:47

    Here's an update for Swift 4 and later that ensure the value entered is an integer in the range 0 to 5000.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let newText = (textField.text! as NSString).replacingCharacters(in: range, with: string) as String
        if let num = Int(newText), num >= 0 && num <= 5000 {
            return true
        } else {
            return false
        }
    }
    
    0 讨论(0)
提交回复
热议问题