Adding space between textfield character when typing in text filed

前端 未结 3 884
太阳男子
太阳男子 2020-12-17 07:14

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

3条回答
  •  醉酒成梦
    2020-12-17 07:38

    Use shouldChangeCharactersIn like this way.

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        if [6, 11, 16].contains(textField.text?.count ?? 0) && string.isEmpty {
            textField.text = String(textField.text!.dropLast())
            return true
        }
        let text = NSString(string: textField.text ?? "").replacingCharacters(in: range, with: string).replacingOccurrences(of: "-", with: "")
        if text.count >= 4 && text.count <= 16 {
            var newString = ""
            for i in stride(from: 0, to: text.count, by: 4) {
                let upperBoundIndex = i + 4
                let lowerBound = String.Index.init(encodedOffset: i)
                let upperBound = String.Index.init(encodedOffset: upperBoundIndex)
                if upperBoundIndex <= text.count  {
                    newString += String(text[lowerBound.. 19 {
                       newString = String(newString.dropLast())
                    }
                }
                else if i <= text.count {
                    newString += String(text[lowerBound...])
                }
            }
            textField.text = newString
            return false
        }
        if text.count > 16 {
            return false
        }
        return true
    }
    

    Note: I have used - (Hyphen) you can simply replace it with Space if you want Space instead of - (Hyphen).

    Edit: Code is edited to latest swift 4.*, for older swift version please check edit history.

提交回复
热议问题