How to set custom font and weight (style) to UInav

2019-07-27 05:43发布

问题:

How to set custom font name and custom font weight (font style) for UINavigationBar title?

回答1:

Try this code. Swift 3x

This could be a better approach to set nanvigationBar title font and Style.

    navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName:UIColor.ANY COLOUR, NSFontAttributeName:UIFont(name:"FontName-FontStyle", size: ANY SIZE)!]

Some Font Styles:

    Regular,Bold,BoldItalic,CondensedBlack,CondensedBold,Italic,Light,LightItalic,Thin,ThinItalic,UltraLight,UltraLightItalic

Note: Font style varies from font to font!



回答2:

Use UIFontDescriptor as Font Name and Font Size

UIFontDescriptor.fontDescriptorWithSymbolicTraits as font style (Bold, Italic, ...)

Swift 2.x:

let fontDec = UIFontDescriptor(name: "FontName", size: 20)
fontDec.fontDescriptorWithSymbolicTraits(.TraitBold)
let font = UIFont(descriptor: fontDec, size: 20)

self.navigationBar.titleTextAttributes = [
    NSFontAttributeName: font,
    NSForegroundColorAttributeName: UIColor.redColor()]

Maybe performance issue.



回答3:

Swift 4x:

let newFont = UIFont(name: "FontName", size: 15) newFont?.fontDescriptor.withSymbolicTraits(.traitBold)