How to get font style name from UIFont in Swift 5.1?
Asked Answered
B

1

7

I need to write a custom font picker view in my ios project. when user click on font family name, i need to display fonts which are in particular family, i used name as particular text style in the family name. I couldn't find the standard way to getting the text style name of the particular name. please, help me to resolve this.

As an example, i have compared print all fonts names and UIFontPickerViewController ios component font names. if i print family name and font name it is looking below for Times New Roman family.

Family name Times New Roman
    Font name: TimesNewRomanPS-ItalicMT
    Font name: TimesNewRomanPS-BoldItalicMT
    Font name: TimesNewRomanPS-BoldMT
    Font name: TimesNewRomanPSMT

But in the UIFontPickerViewController (ios component), it display like this enter image description here

I would like to know , how we can get text style Regular, Italic, Bold, Bold Italic from above printed names ? please, help me and appreciate ur feedback. Please, refer below source code for comparison

import UIKit

class ViewController: UIViewController, UIFontPickerViewControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()
        let familyNames = UIFont.familyNames.sorted()

        for family in familyNames {
            print("Family name " + family)
            let fontNames = UIFont.fontNames(forFamilyName: family)

            for font in fontNames {
                print("    Font name: " + font)
            }
        }
        
        let configuration = UIFontPickerViewController.Configuration()
        configuration.includeFaces = true
        configuration.displayUsingSystemFont = true
        configuration.filteredTraits = [.classModernSerifs]
        let vc = UIFontPickerViewController(configuration: configuration)
        vc.delegate = self
        present(vc, animated: true)
        
        
    }


}
Bricker answered 30/7, 2020 at 5:48 Comment(2)
Seems like you need to manually add label font with a custom font.Fishbolt
Ohh ok, but it is not practical for all ios fonts.Bricker
D
1

I had the same question, and the answer was only hard to find because I should have been referring to it as font "face" rather than font "style".

Anyhow, here's the current way one gets the font face / font style name in Swift 5.7:

font.fontDescriptor.object(forKey: .face) as? String

I've created a small extension to UIFont for returning font face/style.

public extension UIFont {

    /// Gets the font style (face) name
    var fontStyle: String {
        return fontFace
    }

    /// Gets the font face name
    var fontFace: String {
        return (fontDescriptor.object(forKey: .face) as? String) ?? fontDescriptor.postscriptName
    }
}
Duck answered 31/10, 2022 at 15:27 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.