【发布时间】:2018-10-24 00:16:52
【问题描述】:
我正在创建一个测验类型的应用程序。用户需要在UITextField 中提供输入。所以我必须检查以下条件:
限制用户只能使用数字和 $ (
Like "0123456789$")。在文本字段中添加逗号。
$应该只在文本字段值中出现一次,并且在任何数字之后也是如此。这意味着用户无法从$开始输入。在
$之后,如果用户输入任何数字,那么我必须显示“数字格式不正确”这样的弹出窗口。
这是我的代码:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool{
//Solution for 1st condition
let inverseSet = NSCharacterSet(charactersIn:"0123456789$").inverted
let components = string.components(separatedBy: inverseSet)
let filtered = components.joined(separator: "")
if filtered == string {
return true
} else {
if string == "." {
let countdots = textField.text!.components(separatedBy:".").count - 1
if countdots == 0 {
return true
}else{
if countdots > 0 && string == "." {
return false
} else {
return true
}
}
}else{
return false
}
}
}
//Solution for 2nd condition
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.locale = Locale.current
formatter.maximumFractionDigits = 0
if let groupingSeparator = formatter.groupingSeparator {
if string == groupingSeparator {
return true
}
if let textWithoutGroupingSeparator = textField.text?.replacingOccurrences(of: groupingSeparator, with: "") {
var totalTextWithoutGroupingSeparators = textWithoutGroupingSeparator + string
if string == "" { // pressed Backspace key
totalTextWithoutGroupingSeparators.characters.removeLast()
}
if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators),
let formattedText = formatter.string(from: numberWithoutGroupingSeparator) {
textField.text = formattedText
return false
}
}
}
return true
}
}
如何在UITextField shouldChangeCharactersIn 方法中设置多个条件。请帮助我实现这一目标。谢谢!
【问题讨论】:
标签: ios swift3 uitextfield