Adding space between textfield character when typing in text filed

ava

I have a textfield with maximum character range 16, After every 4 characters, I want to add minus character or space and then writing The rest of the characters like this sample 5022-2222-2222-2222. there is my code but that's don't work, how can do this?

if textField.text?.characters.count  == 5 {

               let  l = textField.text?.characters.count
            let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
            attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
            cartNumberTextField.attributedText = attributedString

            }

            else if textField.text?.characters.count  == 9 {

                let  l = textField.text?.characters.count
                let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
                attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
                cartNumberTextField.attributedText = attributedString

            }

            else if textField.text?.characters.count  == 13 {

                let  l = textField.text?.characters.count
                let attributedString = NSMutableAttributedString(string: cartNumberTextField.text!)
                attributedString.addAttribute(NSKernAttributeName, value: CGFloat(4.0), range: NSRange(location: l!, length: 4))
                cartNumberTextField.attributedText = attributedString

            }

I am adding this code in UITextField shouldChangeCharactersIn range method.

dfrib

We may start by implementing a Swift 3 version of the chunk(n:) method (for Collection's) of oisdk:s SwiftSequence:

/* Swift 3 version of Github use oisdk:s SwiftSequence's 'chunk' method:
   https://github.com/oisdk/SwiftSequence/blob/master/Sources/ChunkWindowSplit.swift */
extension Collection {
    public func chunk(n: IndexDistance) -> [SubSequence] {
        var res: [SubSequence] = []
        var i = startIndex
        var j: Index
        while i != endIndex {
            j = index(i, offsetBy: n, limitedBy: endIndex) ?? endIndex
            res.append(self[i..<j])
            i = j
        }
        return res
    }
}

In which case implementing your custom formatting is a simple case of creating 4-character chunks and joining these by "-":

func customStringFormatting(of str: String) -> String {
    return str.characters.chunk(n: 4)
        .map{ String($0) }.joined(separator: "-")
}

Example usage:

print(customStringFormatting(of: "5022222222222222")) // 5022-2222-2222-2222
print(customStringFormatting(of: "50222222222222"))   // 5022-2222-2222-22
print(customStringFormatting(of: "5022222"))          // 5022-222

If applying to be used in the textField(_:shouldChangeCharactersIn:replacementString:) method of UITextFieldDelegate, we might want to filter out existing separators in the customStringFormatting(of:) method method, as well as implementing it as a String extension:

extension String {
    func chunkFormatted(withChunkSize chunkSize: Int = 4, 
        withSeparator separator: Character = "-") -> String {
        return characters.filter { $0 != separator }.chunk(n: chunkSize)
            .map{ String($0) }.joined(separator: String(separator))
    }
}

And implement the controlled updating of the textfield e.g. as follows:

let maxNumberOfCharacters = 16

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    // only allow numerical characters
    guard string.characters.flatMap({ Int(String($0)) }).count ==
        string.characters.count else { return false }

    let text = textField.text ?? ""

    if string.characters.count == 0 {
        textField.text = String(text.characters.dropLast()).chunkFormatted()
    }
    else {
        let newText = String((text + string).characters
            .filter({ $0 != "-" }).prefix(maxNumberOfCharacters))
        textField.text = newText.chunkFormatted()
    }
    return false
}

The last part above will truncate possible pasted strings from the user (given that it's all numeric), e.g.

// current 
1234-1234-123

// user paste:
777777777
  /* ^^^^ will not be included due to truncation */  

// will result in
1234-1234-1237-7777

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

adding space between icon and text in textfield

From Dev

Adding space between image and text in QPushButton

From Dev

Delete specific text from filed with or without a space

From Dev

Append text to textfield while typing

From Dev

JS: Adding a space between Japanese character phrase and number using regex

From Dev

JS: Adding a space between Japanese character phrase and number using regex

From Dev

Split command in Excel VBA adding a space between every character in array

From Dev

Input textfield hidden when not typing

From Dev

Is there a way to avoid automatically adding extra space when typing two consecutive spaces in Word 2010?

From Dev

Placing image after text without adding space between lines

From Dev

Placing image after text without adding space between lines

From Dev

How to get value from a text field when user finish typing or goes out of textfield using jQuery?

From Dev

Adding a space between variables

From Dev

Adding space between images?

From Dev

Adding space between images?

From Dev

Adding space between input

From Dev

Adding a space in excel text

From Dev

Adding Character between numbers

From Dev

PlaceHolder animates when start typing in TextField in iOS

From Java

Flutter adding text into TextField controller

From Dev

Remove space between text and <sup>reference</sup> when text is justified

From Dev

setlayout when dynamic adding textField

From Dev

Adding comma while typing in the text box

From Dev

any character between keywords with a space

From Dev

remove space between character oracle

From Dev

GridBagLayout, adding space between JButtons

From Dev

Adding space between labels and fields

From Dev

Adding space between Strings in Array

From Dev

Adding Space Between DataList Rows

Related Related

  1. 1

    adding space between icon and text in textfield

  2. 2

    Adding space between image and text in QPushButton

  3. 3

    Delete specific text from filed with or without a space

  4. 4

    Append text to textfield while typing

  5. 5

    JS: Adding a space between Japanese character phrase and number using regex

  6. 6

    JS: Adding a space between Japanese character phrase and number using regex

  7. 7

    Split command in Excel VBA adding a space between every character in array

  8. 8

    Input textfield hidden when not typing

  9. 9

    Is there a way to avoid automatically adding extra space when typing two consecutive spaces in Word 2010?

  10. 10

    Placing image after text without adding space between lines

  11. 11

    Placing image after text without adding space between lines

  12. 12

    How to get value from a text field when user finish typing or goes out of textfield using jQuery?

  13. 13

    Adding a space between variables

  14. 14

    Adding space between images?

  15. 15

    Adding space between images?

  16. 16

    Adding space between input

  17. 17

    Adding a space in excel text

  18. 18

    Adding Character between numbers

  19. 19

    PlaceHolder animates when start typing in TextField in iOS

  20. 20

    Flutter adding text into TextField controller

  21. 21

    Remove space between text and <sup>reference</sup> when text is justified

  22. 22

    setlayout when dynamic adding textField

  23. 23

    Adding comma while typing in the text box

  24. 24

    any character between keywords with a space

  25. 25

    remove space between character oracle

  26. 26

    GridBagLayout, adding space between JButtons

  27. 27

    Adding space between labels and fields

  28. 28

    Adding space between Strings in Array

  29. 29

    Adding Space Between DataList Rows

HotTag

Archive