我需要为UITextField设置限制,比如只接受2个小数点值并添加自动货币符号。
例如,
23.45美元-对
但是45.4545美元-错了
45.4545.65美元-错误
45.45-错误(如果文本字段有值,则应自动添加货币符号)
我达到了小数点后2位的限制,但我没有得到它与货币符号卡住。
注:
(1)当用户在UITextField中键入时,必须自动添加货币符号
(2)如果没有值,则显示占位符值。(删除货币符号)
(3)UITextField应该接受1点和小数点后2,如$67.89
(4)在UITextFieldDelegate方法中,所有这些条件都应该是可能的。不要使用静态标签或其他东西。
这是我的代码。。。

 //MARK: - UITextFieldDelegate


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

    isEditingMode = true
    switch textField.tag {
    case tag_price_txt:
        let formatter = NumberFormatter()
        formatter.minimumFractionDigits = 2
        formatter.maximumFractionDigits = 2
        formatter.minimumIntegerDigits = 1
        formatter.maximumIntegerDigits = 10

        //var newString = ""

        let aString = textField.text!
        let newStr = aString.replacingOccurrences(of: "£", with: "")
        textField.text = newStr

        let nsString = newStr as NSString?
        let newString:String = (nsString?.replacingCharacters(in: range, with: string))!

        let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
        let regex = try? NSRegularExpression(pattern: expression, options: .caseInsensitive)
        let numberOfMatches: Int? = regex?.numberOfMatches(in: newString, options: [], range: NSRange(location: 0, length: (newString.count)))

      if numberOfMatches != 0 {

                amountTypedString = newString
                let newString1 = "\(SymbolOfCurrency.Pound.rawValue)" +  amountTypedString
                displayAmountString = newString1
                //textField.text = newString1
                print("assigned value",displayAmountString)
                return true
          }else{
            return false
        }

        return true
}

ios - UITextField中带有货币符号的点后限制为小数点后2位-LMLPHP
输入后应如下:
ios - UITextField中带有货币符号的点后限制为小数点后2位-LMLPHP
请帮忙。提前谢谢。

最佳答案

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let dotString = "."
    let character = "£"

    if let text = textField.text{
        if !text.contains(character){
            textField.text = "\(character) \(text)"
        }
        let isDeleteKey = string.isEmpty

        if !isDeleteKey {
            if text.contains(dotString) {
                if text.components(separatedBy: dotString)[1].count == 2 || string == "."  {
                    return false
                }
            }
        }
    }
    return true
}

关于ios - UITextField中带有货币符号的点后限制为小数点后2位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49003390/

10-13 03:48