我试图制作一个只能接受数字的自定义 UITextField,但逗号后的数字数量有限。所以如果用户输入:
0 -> 0
10 -> 10
10,0 -> 10,0
1000 -> 1.000
0,1 -> 0,1
0,00000008 -> 0,00000008
1,000006 -> 1,000006
10000,12345678 -> 10.000,12345678
用户必须输入逗号,以便计算逗号后面的数字,但如果他不输入,它总是一个整数。逗号后的最大字符数为 8。
已经尝试了一些 textField 委托方法,但没有任何成功:
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let characterSet = NSCharacterSet(charactersIn: "0123456789,").inverted
let filtered = string.components(separatedBy: characterSet)
let component = filtered.joined(separator: "")
let isNumeric = string == component
if isNumeric {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 8
formatter.groupingSeparator = "."
formatter.decimalSeparator = ","
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.isEmpty {
totalTextWithoutGroupingSeparators.removeLast()
}
if let numberWithoutGroupingSeparator = formatter.number(from: totalTextWithoutGroupingSeparators),
let formattedText = formatter.string(from: numberWithoutGroupingSeparator) {
textField.text = formattedText
return false
}
}
}
}
return true
}