如何在Swift 5.1中从UIFont获取字体样式名称?

7
我需要在我的iOS项目中编写一个自定义字体选择器视图。当用户点击字体族名称时,我需要显示该族的字体,我把族名作为特定文本样式。但我无法找到获取特定名称文本样式名称的标准方法,请帮助我解决这个问题。
例如,我已经比较了所有字体名称和UIFontPickerViewController iOS组件的字体名称。 如果我打印族名和字体名称,如下所示,针对Times New Roman族。
Family name Times New Roman
    Font name: TimesNewRomanPS-ItalicMT
    Font name: TimesNewRomanPS-BoldItalicMT
    Font name: TimesNewRomanPS-BoldMT
    Font name: TimesNewRomanPSMT

但是在UIFontPickerViewController(iOS组件)中,它显示为如下形式: enter image description here

我想知道,我们怎样从上面打印的名称中获取文本样式Regular, Italic, Bold, Bold Italic? 请帮忙解答并感谢您的反馈。 以下是源代码以供比较。

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)
        
        
    }


}

1
似乎您需要手动添加自定义字体的标签字体。 - Faysal Ahmed
1
哦,好的,但这对于所有iOS字体来说并不实用。 - Dileepa Chandrasekara
1个回答

1

我曾经有同样的问题,答案之所以难以找到,是因为我应该将其称为字体“face”,而不是字体“style”。

无论如何,以下是在Swift 5.7中获取字体face / 字体style名称的当前方法:

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

我创建了一个小扩展来返回字体的面/样式,它与UIFont相关。
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
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接