swiftuitextfieldletter-spacing

Space between characters in UITextField


How can I add space between characters? (hundred, thousand, million) For example

550
5 500
55 500
555 500
5 555 000 etc.

I did this

@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) )
    }
}

but it doesn't work properly

5 000
5 00000

then deleting with new spaces

5 000...0


Solution

  • There is multiple ways to accomplish what you want. You can use a NumberFormatter or manually insert the spaces. First remove all non digits characters from your text field and then format or insert a space where every 3rd digit except in the first and last positions:

    @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!)
    }
    

    Playground testing:

    let tf = UITextField()
    ["","5","55","550","5500","55500","555500","5555000"].forEach { text in
        tf.text = text
        textEditingChanged(tf)
    }
    

    This will print:

    5
    55
    550
    5 500
    55 500
    555 500
    5 555 000