'Adding space between textfield character when typing in text filed
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.
Solution 1:[1]
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..<upperBound]) + "-"
if newString.count > 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.
Solution 2:[2]
To do it "on the fly", I connected Editing changed to this IBAction ; needs also to care for backspace
@IBAction func editingTestField(_ sender: UITextField) {
if sender.text!.count > 0 && sender.text!.count % 5 == 0 && sender.text!.last! != "-" {
sender.text!.insert("-", at:sender.text!.index(sender.text!.startIndex, offsetBy: sender.text!.count-1) )
}
}
Solution 3:[3]
Took @claude31's simple solution and cleaned it up a bit. Also avoids issues with leading/trailing whitespace now. Just hook it up to your UITextField's Editing Changed event.
@IBAction func editingTextField(_ sender: UITextField) {
let text = sender.text?.trim ?? ""
if !text.isEmpty && text.count % 5 == 0 && text.last != "-" {
sender.text = text // trim whitespace before appending
sender.text?.insert("-", at: text.index(text.startIndex, offsetBy: text.count - 1))
}
}
Solution 4:[4]
Swift-5 conversion of @dfrib's answer.
extension Collection {
public func chunk(n: Int) -> [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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | claude31 |
| Solution 3 | Kyle Johnson |
| Solution 4 | AshWinee Dhakad |
