zevij
zevij

Reputation: 2446

How to access the iOS system font programmatically

I am trying to change the font size of the title of a navigation bar. I know I can set its attributes using:

var attributes = [ NSForegroundColorAttributeName: UIColor.blackColor(), NSFontAttributeName: UIFont(name: "the font name", size: 18)! ]

...

 self.navigationController?.navigationBar.titleTextAttributes = attributes

What I cannot seem to find is the correct 'System' font name.

I was after the default, a.k.a System, font name. I tried printing all the available fonts only to discover it does not belong to a family and does not seem to have an explicit name.

Upvotes: 57

Views: 63323

Answers (8)

Yaroslav Dukal
Yaroslav Dukal

Reputation: 3932

SWIFT 4+: shorter version

UIFont.systemFont(ofSize: 14.0, weight: .regular)

Upvotes: 18

Justin
Justin

Reputation: 2056

Besides all the answers, it's a better idea to use system font with system styles instead of defining custom sizes and weights. To access them programmatically, for example for the headline, you can use this method:

let font = UIFont.preferredFont(forTextStyle: .headline)

I know it is a valid code at least for Swift 5.

Upvotes: 4

Phil
Phil

Reputation: 1577

You can access the system font like this, and even set the weight of the font:

  • Swift 3, Swift 4

    UIFont.systemFont(ofSize: 18, weight: UIFontWeightLight)

  • Swift 2

    UIFont.systemFontOfSize(18, weight: UIFontWeightLight)

For the font weight you have the choice between those constants, there available from iOS 8.2:

UIFontWeightUltraLight,
UIFontWeightThin,
UIFontWeightLight,
UIFontWeightRegular,
UIFontWeightMedium,
UIFontWeightSemibold,
UIFontWeightBold,
UIFontWeightHeavy,
UIFontWeightBlack

Upvotes: 30

Vincent
Vincent

Reputation: 4409

(In line with the answer from Philippe for the latest version)

  • Swift 4

    UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.light)

Upvotes: 6

Zp1k_e
Zp1k_e

Reputation: 128

Just use methods of UIFont (swift):

let sysFont: UIFont = UIFont.systemFontOfSize(UIFont.systemFontSize())

Hope it helps!

Upvotes: 2

Sujith Chandran
Sujith Chandran

Reputation: 2721

self.navigationController?.navigationBar.titleTextAttributes = [NSFontAttributeName : UIFont.systemFontOfSize(6)]

Upvotes: 2

Aditi Agrawal
Aditi Agrawal

Reputation: 101

Try the below code:

self.navigationController!.navigationBar.titleTextAttributes = [NSFontAttributeName: UIFont(name:"Arial", size:14.0)!, NSForegroundColorAttributeName:UIColor.blackColor()]

Upvotes: 0

Roland Keesom
Roland Keesom

Reputation: 8288

I think you need:

NSFontAttributeName : UIFont.systemFontOfSize(19.0)

Or the bold version:

NSFontAttributeName : UIFont.boldSystemFontOfSize(19.0)

See this guide for more info on user interface guidelines and fonts.

Upvotes: 113

Related Questions