Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set letter spacing of UITextField

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

like image 210
KMV Avatar asked Aug 07 '15 11:08

KMV


People also ask

How do I add a space between text in Swift?

The two modifiers are tracking() and kerning() : both add spacing between letters, but tracking will pull apart ligatures whereas kerning will not, and kerning will leave some trailing whitespace whereas tracking will not.

How do I add padding to textfield?

The important methods of a JTextField class are setText(), getText(), setBorder(), setEnabled(), etc. We can add padding to a JTextField using the setMargin(Insets s) of JTextComponent class.


1 Answers

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) 
like image 127
iOSer Avatar answered Sep 22 '22 14:09

iOSer