@almas-adlibek 最佳答案的 Swift 4.2 端口
一堆配置变量:
private let kMaxTextLength = 8
private let kZeroDotted = "0."
private let kZero = "0"
private let kDoubleDot = ".."
private let kDot = "."
private let kPeriod = ","
现在 Swift 4 转换了部分代码。
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let oldText = textField.text, let swiftRange = Range(range, in: oldText) else {
return true
}
let newText = oldText.replacingCharacters(in: swiftRange, with: string)
var currentText = textField.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
// Change the "," (appears in other locale keyboards, such as russian) key ot "."
currentText = currentText?.replacingOccurrences(of: kPeriod, with: kDot)
// Check the statements of decimal value.
if (newText == kDot) {
textField.text = kZeroDotted;
return false
}
if (newText.range(of: kDoubleDot) != nil) {
textField.text = newText.replacingOccurrences(of: kDoubleDot, with: kDot);
return false
}
// If second dot is typed, ignore it.
let dots = newText.components(separatedBy: kDot)
if(dots.count > 2) {
textField.text = currentText;
return false
}
// If first character is zero and second character is > 0, replace first with second. 05 => 5;
if(newText.count == 2) {
if(newText[0...0] == kZero && newText != kZeroDotted) {
textField.text = newText[1...1]
return false
}
}
// Check the max characters typed.
let oldLength = textField.text?.count ?? 0
let replacementLength = string.count
let rangeLength = range.length
let newLength = oldLength - rangeLength + replacementLength;
let returnKey = string.rangeOfCharacter(from: CharacterSet.newlines) != nil
return newLength <= kMaxTextLength || returnKey;
}