如何在 iOS 中将文本字段分隔为数字格式逗号?
How to separate a textfield into a number format comma in iOS?
我希望数字是 12,345,678,所以当我在文本字段中输入时,它就会出现。文本框的最大输入值为8位。
我用了下面的代码,但是输入7位数字后无法清除数字
我该如何解决?
override func viewDidLoad() {
myTextfield.delegate = self
self.myTextfield.keyboardType = .numberPad
myTextfield.addTarget(self, action:#selector(textFieldValDidChange), for: .editingChanged)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 8
}
@objc func textFieldValDidChange(_ textField: UITextField) {
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
if textField.text!.count >= 1 {
let number = Double(textField.text!.replacingOccurrences(of: ",", with: ""))
let result = formatter.string(from: NSNumber(value: number!))
textField.text = result!
}
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 10
}
8 位数字加 2 个逗号,即 10 个字符(最后索引为 9)。
当有7个数字和两个逗号时,光标在最后,range.location
就是9。所以用:
return range.location <= 9
这将允许 8 位数字和两个逗号。
但即便如此,你的支票还是不够的。用户可以将光标移动到数字的开头并输入更多数字。所以仅仅检查光标的位置是不够的。您想检查结果字符串的长度。
您的代码也没有采取任何措施来防止输入非数字文本。用户可以复制和粘贴,用户可以使用外部键盘。而在 iPad 上,.numberPad
键盘仍然显示正常的全键盘。永远不要依赖分配的键盘。
总结 - 更新 shouldChangeCharactersIn
以确保只输入数字并查看字符串的最终长度,光标位置无关紧要。
我希望数字是 12,345,678,所以当我在文本字段中输入时,它就会出现。文本框的最大输入值为8位。
我用了下面的代码,但是输入7位数字后无法清除数字
我该如何解决?
override func viewDidLoad() {
myTextfield.delegate = self
self.myTextfield.keyboardType = .numberPad
myTextfield.addTarget(self, action:#selector(textFieldValDidChange), for: .editingChanged)
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 8
}
@objc func textFieldValDidChange(_ textField: UITextField) {
let formatter = NumberFormatter()
formatter.numberStyle = NumberFormatter.Style.decimal
if textField.text!.count >= 1 {
let number = Double(textField.text!.replacingOccurrences(of: ",", with: ""))
let result = formatter.string(from: NSNumber(value: number!))
textField.text = result!
}
}
public func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
return range.location < 10
}
8 位数字加 2 个逗号,即 10 个字符(最后索引为 9)。
当有7个数字和两个逗号时,光标在最后,range.location
就是9。所以用:
return range.location <= 9
这将允许 8 位数字和两个逗号。
但即便如此,你的支票还是不够的。用户可以将光标移动到数字的开头并输入更多数字。所以仅仅检查光标的位置是不够的。您想检查结果字符串的长度。
您的代码也没有采取任何措施来防止输入非数字文本。用户可以复制和粘贴,用户可以使用外部键盘。而在 iPad 上,.numberPad
键盘仍然显示正常的全键盘。永远不要依赖分配的键盘。
总结 - 更新 shouldChangeCharactersIn
以确保只输入数字并查看字符串的最终长度,光标位置无关紧要。