如何限制文本字段小数

How to limit textfield decimal

如何限制多个UItextField的长度:

最大整数允许两位,最大小数允许一位。

我使用此代码将文本限制为两个数字:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

var kMaxLength = 2
let oldString = textFieldlOne.text as NSString

let string = oldString.stringByReplacingCharactersInRange(range, withString: string)


return countElements(string) <= kMaxLength

 }

但是我有几个 UITextfield IBOutlet,我想允许用户插入一个十进制数 es。 12.5

目前我还不太熟悉swift。所以我先尝试在Obj-C中解决。

#define MAX_BEFORE_DECIMAL_DIGITS = 2
#define MAX_AFTER_DECIMAL_DIGITS = 1

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range  replacementString:(NSString *)string {

NSString *computationString = [textField.text stringByReplacingCharactersInRange:range withString:string];

// Take number of digits present after the decimal point.
NSArray  *arrayOfSubStrings = [newString componentsSeparatedByString:@"."];

if(([arrayOfSubStrings count] == 1) && (computationString.length > MAX_BEFORE_DECIMAL_DIGITS)) {
    return NO;
} else if([arrayOfSubStrings count] == 2) {
    NSString *stringPostDecimal = [NSString stringWithFormat:@"%@",[arrayOfSubStrings objectAtIndex:1]];
    return !([stringPostDecimal length] > MAX_AFTER_DECIMAL_DIGITS);
}

return YES;
}

根据您的要求定义 MAX_BEFORE_DECIMAL_DIGITS 和 MAX_AFTER_DECIMAL_DIGITS 的值。

这是来自@Vijayts 回答的 swift 转换:

struct Constants {
  static let MAX_BEFORE_DECIMAL_DIGITS = 2
  static let MAX_AFTER_DECIMAL_DIGITS = 1
}

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
  let computationString = (textField.text! as NSString).stringByReplacingCharactersInRange(range, withString: string)

  // Take number of digits present after the decimal point.
  let arrayOfSubStrings = computationString.componentsSeparatedByString(".")

  if arrayOfSubStrings.count == 1 && computationString.characters.count > Constants.MAX_BEFORE_DECIMAL_DIGITS {
    return false
  } else if arrayOfSubStrings.count == 2 {
    let stringPostDecimal = arrayOfSubStrings[1]
    return stringPostDecimal.characters.count <= Constants.MAX_AFTER_DECIMAL_DIGITS
  }

  return true
}

在尝试测试字符串是否与特定模板匹配时,正则表达式很有用:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldString = textField.text ?? "" as NSString
    let candidate = oldString.stringByReplacingCharactersInRange(range, withString: string)
    let regex = try? NSRegularExpression(pattern: "^\d{0,2}(\.\d?)?$", options: [])
    return regex?.firstMatchInString(candidate, options: [], range: NSRange(location: 0, length: candidate.characters.count)) != nil
}

\d{0,2}匹配零到两位数字。 (\.\d?)? 转换为 "if there is a decimal point, allow it and optionally one more digit."(您也可以 (\.\d{0,1})?。)^ 匹配 "start of the string",$ 匹配 "end of the string"(即,我们只会找到 \d{0,2}(\.\d?)? 是整个字符串的匹配项,而不仅仅是出现在字符串中间的内容。)当然,所有这些 \ 个字符在字符串文字中被转义为 \

当您第一次接触正则表达式 (regex) 时可能有点 "dense",但是一旦您熟悉了语法,它就是一个非常强大的工具。

--

顺便说一句,我注意到您在评论中说您使用的是 Swift 1.1。我相信等效的 Swift 1.1 语法类似于:

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
    let oldString = textField.text as NSString
    let candidate = oldString.stringByReplacingCharactersInRange(range, withString: string)
    var error: NSError?
    let regex = NSRegularExpression(pattern: "^\d{0,2}(\.\d?)?$", options: 0, error: &error)
    return regex?.firstMatchInString(candidate, options: 0, range: NSRange(location: 0, length: candidate.length)) != nil
}

我没有现成的 Swift 1.1 编译器,所以我不能轻易地 test/confirm 这个 Swift 1.1 语法,但如果我没记错的话,它类似于那。就我个人而言,我建议升级到最新版本的 Xcode,但每个人都有自己的。

Swift 4

使用数字格式化程序

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let s = (textField.text ?? "").appending(string)
        let numberFormatter = NumberFormatter()
        numberFormatter.numberStyle = .decimal
        return numberFormatter.number(from: s)?.doubleValue != nil
    }

在swift 3、限制textfield的输入值在小数点前后

let digitBeforeDecimal = 2
let digitAfterDecimal = 2
func textField(_ textField: UITextField, shouldChangeCharactersIn   range: NSRange, replacementString string: String) -> Bool {
    let computationString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    let arrayOfSubStrings = computationString.components(separatedBy: ".")
    if arrayOfSubStrings.count == 1 && computationString.count > digitBeforeDecimal {//
        return false
    } else if arrayOfSubStrings.count == 2 {
        let stringPostDecimal = arrayOfSubStrings[1]
        return stringPostDecimal.count <= digitAfterDecimal
    }
    return true
}