美文网首页
Swift限制UITextField位数及小数点位数

Swift限制UITextField位数及小数点位数

作者: 鄒賢 | 来源:发表于2023-03-16 11:18 被阅读0次
///限制小数点后两位
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {

        guard string == "." || string == "0" else {
            let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            if newString.range(of: ".") == nil {
                if (newString as NSString).length > 1 && newString.hasPrefix("0") {
                   return false
               }
            }
            return newString.isValidAmount()
        }
        guard let text = textField.text else { return true }
        if text.count == 0 {
            textField.text = "0."
            return false
        }
        if text.range(of: ".") == nil && string == "0" {
            let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
            if !text.hasPrefix("0") && newString.isValidAmount() {
                return true
            }
            return false
        }
        if text.range(of: ".") != nil && string == "." {
            return false
        }
        if text.range(of: ".") != nil {
            let list = textField.text!.components(separatedBy: ".")
            let last = list.last!
            return (last as NSString).length < 2
        }
        return true
       }

extension String {
    public func isValidAmount() -> Bool {
        let expression = "^[0-9]{0,9}?$*((\\.|,)[0-9]{0,2})?$"
        let regex = try! NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
        let numberOfMatches = regex.numberOfMatches(in: self, options:.reportProgress, range: NSMakeRange(0, (self as NSString).length))
        return numberOfMatches != 0
    }
}

相关文章

网友评论

      本文标题:Swift限制UITextField位数及小数点位数

      本文链接:https://www.haomeiwen.com/subject/inarrdtx.html