ios - 如何在 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)。
推荐阅读
- sqlite - SQLite:如何从表 1 的列中复制数据并根据特定行中数据的 ID 将数据粘贴到表 2 的列中?
- java - 安装在特定操作系统上的 JRE 是否定制为仅在安装它的操作系统上运行?
- r - 三、data.table合并行为不一致
- html - 如何从客户端上传图片?
- javascript - 让 Node.JS 服务器实时更新 FireBase 数据库的最佳方式?
- git - 如何返回 git master 分支?
- accessibility - ARIA 可访问性问题
- c# - DropDownListFor 将值 NULL 发布到数据库
- html - 如何在移动设备上堆叠排序的列而在桌面上没有间隙?
- r - 当函数生成某些参数的重复/三次时如何为 UI 报告自定义函数 [r]