ios - Swift3 iOS 中的 UITextField 中只允许使用数字和点字符
问题描述
我正在对我的 UITextField 进行验证。它应该只接受数字和。特点。基本上用户可以输入任何十进制数字,例如:
1.0
1.23
1.45
12.47
我还必须在文本字段中编辑时添加 % 符号,如下所示:
When User enter 1, textfield should update 1 %
When User enter 1.2, textfield should update 1.2 %
When User enter 18.345, textfield should update 18.345 %
我正在使用下面的代码来实现这一点:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if string.characters.count == 0 {
return true
}
do {
if textField == self.questionTextFeild {
let nString = textField.text as NSString?
let newString = nString?.replacingCharacters(in: range, with: string)
let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.characters.count)!))
//textField.text = textField.text!
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
}
return true
}
使用它我可以输入数字和点字符。我的问题是如何添加 % 符号?请给我建议。
解决方案
请找到更新的代码,以便在键入时将百分比添加到数字的最后一个
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
if string.count == 0 {
return true
}
do {
if textField == textField {
let nString = textField.text as NSString?
let newString = nString?.replacingCharacters(in: range, with: string)
if var textString = textField.text {
let unitString = " %"
if textString.contains(unitString) {
textString = textString.replacingOccurrences(of: unitString, with: "")
textString += string + unitString
textField.text = textString
} else {
textField.text = string + unitString
}
}
let expression = "^([0-9]+)?(\\.([0-9]{1,8})?)?$"
let regex = try NSRegularExpression(pattern: expression, options: .caseInsensitive)
let numberOfMatches = regex.numberOfMatches(in: newString! as String, options: [], range: NSRange(location: 0, length: (newString?.count)!))
//textField.text = textField.text!
if numberOfMatches == 0 {
return false
}
}
}
catch let error {
print(error.localizedDescription)
}
return true
}
推荐阅读
- android-studio - Android Studio 错误:无法从 'file:/C:/Users/~/gradle/wrapper/' 安装 Gradle 发行版
- html - 图像模糊
- excel - 如何用特定的 Header 和 Number 填充数据?
- python - 遍历列表中的字典
- ios - 如何在 SwiftUI 中访问安全区域大小?
- java - Java - 如何正确获取和添加 cookie 以请求标头?
- geolocation - 如何通过服务器端的 IP 地址估计用户位置?
- python - 如何使用列表推导替换字符串中的字符?
- php - keycloak登录后如何获取用户信息
- python - 为每 1000 的倍数重置 Pandas Cumsum