Abris
Abris

Reputation: 1481

UITextField font-size when content and losing focus

I have a UITextField for which I would like to assign a custom font and font-size like this

self.txtEmail.font = UIFont("HelveticaNeue-Light", size: 24)

When I start the app everything looks good. My placeholder text gets the new font and if I click on the input field and start typing, the text has the new font. However, when I click somewhere else and the input field lose focus the font is reset to the default font. What I find even more strange is that I only have set this default font for UILabels and not UITextField by adding this line in the application method inside AppDelegate. If I try to set the default font for UITextField nothing happens.

UILabel.appearance().font = UIFont(name: "HelveticeNeue", size: 18)

So my question is why I get the behavior where the UITextField has the correct font until it gets content and lose focus.

Upvotes: 1

Views: 480

Answers (1)

Arthur Gevorkyan
Arthur Gevorkyan

Reputation: 2107

I have 1 general remark on UI elements' appearance management and one more on UITextField. A) Appearance:

The documentation says:

To customize the appearance of all instances of a class, use appearance to get the appearance proxy for the class.

In fact, that means that your changes will be applied to every instance of UILabel that enter your application window (as an iOS app has only 1 "public" window). If you want to customize the appearance of labels contained within a particular container class (e. g. inside UIView), you should consider using + appearanceForTraitCollection:whenContainedIn: (unfortunately, it's been deprecated since iOS 9.0). A much safer way is to use inheritance for your purposes as follows: MySpecialLabel -[inherits from and applies custom style attributes within its initializers and/or the awakeFromNib: method]-> UILabel.

B) Why is it related to UITextField?

That's because UITextField utilizes UILabels under the hood (like _placeholderLabel and _promptLabel).

I hope it will help you solve your problem.

Upvotes: 1

Related Questions