I want to format a UITextField for entering a credit card number into such that it only allows digits to be entered and automatically inserts spaces so that the
Swift 5.1, Xcode 11
After trying many solutions, I faced issues such as setting correct cursor position and formating as per need, I finally found a solution after combining 2 posts (https://stackoverflow.com/a/38838740/10579134, https://stackoverflow.com/a/45297778/10579134)
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
guard let currentText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) else { return true }
if textField == yourTextField {
textField.setText(to: currentText.grouping(every: 4, with: "-"), preservingCursor: true)
return false
}
return true
}
And adding this extension
extension UITextField {
public func setText(to newText: String, preservingCursor: Bool) {
if preservingCursor {
let cursorPosition = offset(from: beginningOfDocument, to: selectedTextRange!.start) + newText.count - (text?.count ?? 0)
text = newText
if let newPosition = self.position(from: beginningOfDocument, offset: cursorPosition) {
selectedTextRange = textRange(from: newPosition, to: newPosition)
}
}
else {
text = newText
}
}