Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting secure text entry by inserting visible spaces

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.

like image 524
Zia Avatar asked Jul 15 '16 17:07

Zia


1 Answers

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).

like image 102
Sebastien Windal Avatar answered Oct 25 '22 03:10

Sebastien Windal