将max int值(不是字符数)设置为UITextField [英] Setting a max int value (not character count) to a UITextField

查看:119
本文介绍了将max int值(不是字符数)设置为UITextField的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift中,是否可以将最大INT值设置为UITextField?

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

我的用例是我有5个需要最大的文本字段int值。这些值的范围从500到10,000。 5个不同的文本字段中的每一个都具有不同的最大值。我不能使用选择器或下拉菜单,因为增量将为1.并且UISlider太难以擦入数字。

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.

如果max int值为5,000,用户无法键入(在数字键盘的键盘类型上)任何高于5000的值。

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.

字符数不起作用,因为如果最大值为500,如果我设置为3个字符,则用户可以键入999.

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

推荐答案

您可以检查是否文本字段中的当前值小于您指定的最大整数值:

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

(您可能希望将键盘类型更改为 .NumberPad 此时只允许用户输入数字值。)

(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.

这篇关于将max int值(不是字符数)设置为UITextField的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆