如何解决UITextField 中字符之间的空格
如何在字符之间添加空格? (十、千、百万) 例如
550
5 500
55500
555 500
5 555 000 等
我做到了
@IBAction func textEditingChanged(_ sender: UITextField) {
if sender.text!.count > 0 && sender.text!.count % 4 == 0 && sender.text!.last! != " " {
sender.text!.insert(" ",at:sender.text!.index(sender.text!.startIndex,offsetBy: sender.text!.count-3) )
}
}
但它不能正常工作
5000
5 00000
然后用新空格删除
5 000...0
解决方法
有多种方法可以实现您的愿望。您可以使用 NumberFormatter 或手动插入空格。首先从您的文本字段中删除所有非数字字符,然后格式化或插入一个空格,其中除了第一个和最后一个位置外,每第三个数字:
@IBAction func textEditingChanged(_ sender: UITextField) {
sender.text!.removeAll { !("0"..."9" ~= $0) }
let text = sender.text!
for index in text.indices.reversed() {
if text.distance(from: text.endIndex,to: index).isMultiple(of: 3) &&
index != text.startIndex &&
index != text.endIndex {
sender.text!.insert(" ",at: index)
}
}
print(sender.text!)
}
游乐场测试:
let tf = UITextField()
["","5","55","550","5500","55500","555500","5555000"].forEach { text in
tf.text = text
textEditingChanged(tf)
}
这将打印:
5
55
550
5 500
55500
555 500
5 555 000
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。