How to set letter spacing of UITextField

KMV picture KMV · Aug 7, 2015 · Viewed 17.8k times · Source

I have an app in which the user has to type a four digit pin code. All digits have to be at a set distance from each other.

Is there a way to do this if the PinTextField is a subclass of UIView? I know in a ViewController you could use UITextFieldTextDidChangeNotification and set the attributed text for each change. Notifications don't seem to work in a UIView though.

Also I was wondering if there isn't a simpler way than making an attributed string for every update if you want to set the letter spacing of a UITextField text ?

Correct spacing:

TextField with correct spacing

Wrong spacing:

TextField with wrong spacing

Answer

iOSer picture iOSer · Feb 1, 2018

No need to go for attributedText, which to be honest, was a mess implementing with modified spacing. As soon as I closed the keyboard the spacing disappeared, which prompted me to dig further.

Every UITextField has a property called defaultTextAttributes, which according to Apple "returns a dictionary of text attributes with default values.". The Apple document also says that "this property applies the specified attributes to the entire text of the text field"

Just find a suitable place in your code, usually where the textfield is being initialized and then copy and paste the following.

Answered in Swift 3.0

textfield.defaultTextAttributes.updateValue(spacing, forKey: NSKernAttributeName)

where spacing is of CGFloat type. For example 2.0

This works for different fonts as well.

Cheers!!


The latest syntax seems to be:

 yourField.defaultTextAttributes.updateValue(36.0, 
     forKey: NSAttributedString.Key.kern)