How to set letter spacing of UITextField

前端 未结 7 907
[愿得一人]
[愿得一人] 2021-01-30 12:55

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 PinTex

7条回答
  •  后悔当初
    2021-01-30 13:35

    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)
    

提交回复
热议问题