///限制小数点后两位
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位数及小数点位数
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1.设置placeholder颜色 [textField setValue:[UIColor greenColor...
- UITextField的代理方法中添加类似如下代码 - (BOOL)textField:(UITextField ...
- 首先我们需要给需要限制的UITextField设置代理,然后在其代理方法中实现如下的代码: 代码: functex...