I want the user to enter a Social Security Number in the format ••• •• ••••. The user types the first 3 numbers, then I append a space manually. Then they enter 2 more numbers and I manually append a space. Of course, even the spaces are being displayed as •. Is there a native way to change this behavior? I am currently using a funky manual implementation of this.
The simple solution I have been using is to convert my input string to an NSAttributedString with text spacing (.kern) attributes added at the proper locations and keeping isSecureTextEntry set to true. Disabling isSecureTextEntry and doing it by hand in addition of being overly complex could have security implications at least if someone is using a third party keyboard.
var ssnText = "123456789"
let spacerPositions = [ 2, 4 ]
let spacingAmount: CGFloat = 5.0
let spacerRanges:[NSRange] = spacerPositions
.filter { $0 < ssnText.count - 1 }
.map { NSRange(location: $0, length: 1) }
let attributedString = NSMutableAttributedString(string: ssnText)
for range in spacerRanges {
attributedString.addAttribute(.kern, value: spacingAmount, range: range)
}
textField.attributedText = attributedString
calling that stuff in textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With