迅速。在textField中格式化输入

时间:2016-10-25 02:22:31

标签: ios swift uitextfield uitextview number-formatting

我创建了textField,并希望将文本格式化为43/35。号码/号码 - 用于信用卡月份和年份。

我可以使用数字fomatter或我如何更容易地使用它? 这里的问题是,如果我添加新字符,我需要替换第3个字符,如果我删除第2个字符则将其删除。

我不想使用任何第三方库,我需要本机实现

2 个答案:

答案 0 :(得分:3)

这是我目前的解决方案。基本上你需要:

1)在某处实现delegate的{​​{1}}(在我在ViewController上实现的代码中)

2)实施textfield

要应用掩码,我为字符串和字符创建了一些扩展,如下面代码末尾所示:

textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool

答案 1 :(得分:0)

快捷键4:

extension CodeEnterViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        guard let normalText = textField.text else { return false }

        let beginning = textField.beginningOfDocument
        // save cursor location
        let cursorLocation = textField.position(from: beginning, offset: range.location + string.count)

        let newString = (normalText as NSString).replacingCharacters(in: range, with: string)
        let newStringClean = newString.stringWithOnlyNumbers().withMask(mask: mask)

        guard newString != newStringClean else { return true }

        textField.text = newStringClean
        guard string != "" else { return false }

        // fix cursor location after changing textfield.text
        if let cL = cursorLocation {
            let textRange = textField.textRange(from: cL, to: cL)
            textField.selectedTextRange = textRange
        }

        return false
    }
}

字符串

extension String {
    func stringWithOnlyNumbers() -> String {
        return self.reduce("") { (acc, c) -> String in
            guard c.isDigit() else { return acc }
            return "\(acc)\(c)"
        }
    }

    func withMask(mask: String) -> String {
        var resultString = String()

        let chars = self
        let maskChars = mask

        var stringIndex = chars.startIndex
        var maskIndex = mask.startIndex

        while stringIndex < chars.endIndex && maskIndex < maskChars.endIndex {
            if (maskChars[maskIndex] == "#") {
                resultString.append(chars[stringIndex])
                stringIndex = chars.index(after: stringIndex)
            } else {
                resultString.append(maskChars[maskIndex])
            }
            maskIndex = chars.index(after: maskIndex)
        }

        return resultString
    }

}

字符

extension Character {
    func isDigit() -> Bool {
        let s = String(self).unicodeScalars
        let uni = s[s.startIndex]

        let digits = NSCharacterSet.decimalDigits
        let isADigit = digits.hasMember(inPlane: UInt8(uni.value))

        return isADigit
    } }