【问题标题】:Limit the amount of characters inserted into a UITextField [duplicate]限制插入 UITextField 的字符数量 [重复]
【发布时间】:2018-07-02 11:39:31
【问题描述】:

如何更改 UITextField,用户只需添加一个 .后面只有两位数。 -> 点后有两位数字的十进制数。

【问题讨论】:

  • 请不要犹豫,提供到目前为止您尝试过的内容...
  • 请记住,世界上许多人不使用. 作为小数分隔符。

标签: swift uitextfield


【解决方案1】:

使用 UITextFieldDelegate

// MARK:- TEXTFIELD DELEGATE
func textField(_ textField: UITextField,shouldChangeCharactersIn range: NSRange,replacementString string: String) -> Bool
{
    let countdots = (txf_Amount.text?.components(separatedBy: ".").count)! - 1

    if countdots > 0 && string == "."
    {
        return false
    }

    let MAX_BEFORE_DECIMAL_DIGITS = 7
    let MAX_AFTER_DECIMAL_DIGITS = 3
    let computationString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
    // Take number of digits present after the decimal point.
    let arrayOfSubStrings = computationString.components(separatedBy: ".")

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

    return true

}

【讨论】:

  • 这不是一个好的解决方案,因为并非所有用户都使用. 作为小数分隔符。
猜你喜欢
  • 1970-01-01
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
  • 1970-01-01
  • 2022-11-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多