在输入文本字段时在文本字段字符之间添加空格 [英] Adding space between textfield character when typing in text filed

查看:132
本文介绍了在输入文本字段时在文本字段字符之间添加空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个最大字符范围为16的textfield,每4个字符后,我想添加一个减号或空格,然后编写其余的字符,例如此样本5022-2222-2222-2222. 有我的代码,但是那是行不通的,怎么办呢?

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

            }

我正在UITextField shouldChangeCharactersIn范围方法中添加此代码.

I am adding this code in UITextField shouldChangeCharactersIn range method.

推荐答案

我们可以从实现 SwiftSequence :

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

在这种情况下,实现自定义格式是创建4个字符的块并通过-"将其连接的简单情况:

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: "-")
}

示例用法:

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


如果申请在 textField(_:shouldChangeCharactersIn:replacementString:) 方法中使用UITextFieldDelegate,我们可能希望滤除customStringFormatting(of:)方法中的现有分隔符,并将其实现为String扩展名:


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

这篇关于在输入文本字段时在文本字段字符之间添加空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆