需求描述:
- 如果是多位整數(shù), 限制首位不能為0, 整數(shù)位最多9位;
- 首位不能為小數(shù)點(diǎn);
- 如果是小數(shù), 小數(shù)位最多兩位;
代碼片段:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
if textField.text?.count == 1 && string.isEmpty {
return true
}
// [1-9]限制多位整數(shù), 首位的范圍; {0, 8}表示減去第一位, 剩余整數(shù)位的個(gè)數(shù)(如9位整數(shù), 減去第一位剩下8位, 用{0, 8}); 小數(shù)位{0,2}表示小數(shù)位的個(gè)數(shù); Note: 使用過(guò)程自行修改{0, 8}, {0, 2}范圍
let expression = "^[1-9]\\d{0,8}?$*((\\.|,)[0-9]{0,2})?$|^0{1}((\\.|,)[0-9]{0,2})?$"
let regex = try? NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.allowCommentsAndWhitespace)
let numberOfMatches = regex?.numberOfMatches(in: newString, options: .reportProgress, range: NSRange(location: 0, length: (newString as NSString).length))
return numberOfMatches != 0
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者