【问题标题】:Space between characters in UITextFieldUITextField 中字符之间的空格
【发布时间】:2021-02-23 16:31:23
【问题描述】:

如何在字符之间添加空格? (百、千、万) 例如

550
5 500
55 500
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

【问题讨论】:

  • 添加空格的逻辑是什么?在每第三位数字之后?比如几千、几十万等等
  • @SandeepBhandari 是的,完全正确
  • @LeoDabus 没有扩展,拜托
  • 您应该知道,数字之间的间距并不普遍是从右边开始的,以 3 为一组,或使用空格。这些东西中的每一个都可以在其他语言中有所不同。您应该使用 NumberFormatter 来正确执行此操作。

标签: swift uitextfield letter-spacing


【解决方案1】:

有多种方法可以实现您想要的。您可以使用 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
55 500
555 500
5 555 000

【讨论】:

  • 它不能正常工作输入:550000 输出:5 5 0 000
  • 对不起,输入:550000 输出:5 5 0 000
猜你喜欢
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-21
  • 2012-02-07
  • 2012-06-19
  • 2015-03-27
  • 1970-01-01
相关资源
最近更新 更多