货币Swift的文本字段

时间:2017-09-26 07:41:37

标签: ios swift uitextfield

我构建付款应用程序,我希望该文本字段只能:

1)只有一个点

2)点后

不超过2个符号

因为我想在文本字段中添加付款金额,所以没有理由为小货币项目(如美分)添加多个点或添加2个符号。

有没有简单的方法呢?

4 个答案:

答案 0 :(得分:1)

使用UITextFieldDelegate及以下代码

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

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

    let MAX_BEFORE_DECIMAL_DIGITS = 3
    let MAX_AFTER_DECIMAL_DIGITS = 0
    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

}

答案 1 :(得分:1)

这是客观的例子。目前我正在使用它进行货币验证。

NSString类别类

- (BOOL)isValidNumber{

        NSString *regxString = @"^([0-9]*)(\\.([0-9]+)?)?$";
        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regxString
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:nil];
        NSUInteger matchCount = [regex numberOfMatchesInString:self
                                                        options:0
                                                          range:NSMakeRange(0, [self length])];
        if (matchCount == 0){
            return NO;
        }
        return YES;
}

文字字段更改事件

- (void)textFieldDidChange :(UITextField *)textField {


                NSArray *seperatedString = [textField.text componentsSeparatedByString:@"."];
                if ([seperatedString count] > 1) {

                    if ([((NSString *)[seperatedString objectAtIndex:1]) length] > MAX_DECIMAL) {

                        [self textFieldRemoveLast:textField];

                    } else if([textField.text isValidLength:NUMBER_MAX_LIMIT]){

                    } else {


                    }
                }
            }
    }

    - (void)textFieldRemoveLast:(UITextField *)textField {

        if (textField.text.length > 0) {
            textField.text = [textField.text substringToIndex:[textField.text length] - 1];
        }
    }

textfield change事件,我正在检查“。”的数量。并基于此我删除最后一个字符。并且您可以设置最大小数位数。

夫特

func isValidNumber() -> Bool {
    let regxString = "^([0-9]*)(\\.([0-9]+)?)?$"
    let regex = try? NSRegularExpression(pattern: regxString, options: .caseInsensitive)
    let matchCount: Int? = regex?.numberOfMatches(in: self, options: [], range: NSRange(location: 0, length: length()))
    if matchCount == 0 {
        return false
    }
    return true
}

。 separete

var seperatedString = textField.text.components(separatedBy: ".")
    if seperatedString.count > 1 {
        if ((seperatedString[1] as? String)?.count ?? 0) > MAX_DECIMAL {
            textFieldRemoveLast(textField)
        }
        else if textField.text.isValidLength(NUMBER_MAX_LIMIT) {

        }
        else {

        }
    }

删除最后一个

func textFieldRemoveLast(_ textField: UITextField) {
    if (textField.text?.count ?? 0) > 0 {
        textField.text = (textField.text as? NSString)?.substring(to: (textField.text?.count ?? 0) - 1)
    }
}

答案 2 :(得分:0)

试试这个

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if (textField.text?.contains("."))!
    {
      if string == "."
      {
        return false
      }
      else if textField.text?.components(separatedBy: ".")[1].characters.count == 2 && range.length != 1{
        return false
      }
    }
    return true
  }

答案 3 :(得分:0)

  • 用户应该只能写数字
  • 您想要不超过1个点
  • 您只需要两位小数

一种可行的方法:

class ViewController: UIViewController {

    // ...

    // MARK: Life Cycle

    override func viewDidLoad() {
        super.viewDidLoad()

        textField.delegate = self

        // ...
    }

}

extension ViewController : UITextFieldDelegate {

    // MARK: UITextFieldDelegate

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

        guard let text = textField.text else {
            return false
        }

        if (text.components(separatedBy: ".").count > 1 && string == ".") || (text.components(separatedBy: ".").count > 1 && text.components(separatedBy: ".")[1].characters.count >= 2 && string != "") {
            return false
        }

        return string == "" || (string == "." || Float(string) != nil)
    }

}