ios - 在文本字段中键入时在文本字段字符之间添加空格

标签 ios swift uitextfield

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

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 范围方法中添加此代码。

最佳答案

我们可以从实现 chunk(n:) method 的 Swift 3 版本开始。 (对于 Collection 的)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 个字符 block 并通过“-”连接它们的简单情况:

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 扩展名:

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

并实现文本字段的受控更新,例如如下:

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
}

上面的最后一部分将截断用户可能粘贴的字符串(假设它都是数字),例如

// current 
1234-1234-123

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

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

关于ios - 在文本字段中键入时在文本字段字符之间添加空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40946134/

相关文章:

ios - 在 iOS Swift 项目中从 "2015-01-17T20:00Z"创建 NSDate

android - fontSize 在 Unity 中究竟意味着什么?

ios - 命令因信号 : Segmentation fault: 11 (When init) 而失败

ios - 在 Swift iOS 的文本字段中添加分隔符 "-"

ios - 在 Swift 中从字符串中提取某些文本

iphone - 单击 UITextField 时如何调用方法?

ios - 从 URL 加载时应如何处理视网膜/正常图像?

ios - NSCoding 的 Swift 通用方法

swift - 带有 Void 的通用类型别名在 Swift 4 中给出了缺少参数的错误

ios - 如何在 Xcode 中调试 EXC_BREAKPOINT (SIGTRAP)