Swift TextField 金额输入

╰半橙微兮° 2023-06-02 10:41 197阅读 0赞
  1. 1 // MARK: - UITextFieldDelegate
  2. 2 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
  3. 3 guard string == "." || string == "0" else {
  4. 4 //限制输入个数{0,2},0-2
  5. 5 /*
  6. 6 let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
  7. 7
  8. 8 //纯整数,限制只有6位{0,6}。如果是小数,就小数点前6后8位{0,8}
  9. 9 //let expression = "^[0-9]{0,6}?$*((\\.|,)[0-9]{0,8})?$"
  10. 10 let expression = "^[0-9]*((\\.|,)[0-9]{0,2})?$"
  11. 11 let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
  12. 12 let numberOfMatches = regex.numberOfMatches(in: newString, options:.reportProgress, range: NSMakeRange(0, (newString as NSString).length))
  13. 13 return numberOfMatches != 0
  14. 14 */
  15. 15
  16. 16 //无限制
  17. 17 return true
  18. 18 }
  19. 19
  20. 20 guard let text = textField.text else { return true }
  21. 21 if text.count == 0 {
  22. 22 textField.text = "0."
  23. 23 return false
  24. 24 }
  25. 25
  26. 26 if text.range(of: ".") != nil && string == "." {
  27. 27 return false
  28. 28 }
  29. 29
  30. 30 return true
  31. 31 }

转载于:https://www.cnblogs.com/sonofdark/p/11435375.html

发表评论

表情:
评论列表 (有 0 条评论,197人围观)

还没有评论,来说两句吧...

相关阅读