LoginSignup
1
2

More than 3 years have passed since last update.

Swiftでフォント情報を日本語で表示 : macOS

Last updated at Posted at 2020-12-24

実行環境

  • swift5
  • MacOS: BigSur
  • Xcode: 12.2

概要

  • フォントファミリーを取得して日本語にする
  • 使用可能なフォントのスタイル一覧を表示
  • フォント名を日本語で出力する

コード

使用可能なフォントファミリーを取得する

  • fontFamilies  使用可能なフォントファミリー一覧
  • localizedFamilyName  フォントをローカライズする(今回は日本語)
let fontFamilies = NSFontManager.shared.availableFontFamilies
for family in fontFamilies {
    print(family)//フォントファミリー名
    let localizedFamilyName = NSFontManager.shared.localizedName(forFamily: family, face: nil)
    print(localizedFamilyName)//フォントファミリー名(ローカライズ後)
}

説明

NSFontManager.shared.availableFontFamilies

  • 使用可能なフォントファミリーを取得。

localizedName(forFamily:face:)

  • フォントファミリー名をユーザの使う言語にローカライズする

localizedName(forFamily:face:)
Returns a localized string with the name of the specified font family and face, if one exists.

Return Value
A localized string with the name of the specified font family and face, or, if face is nil, the font family only.

AppleDocumentation / NSFontmanagerより 

引数face:にnilを渡すとローカライズされたフォントファミリーだけが取得できます。

使用可能なフォントのスタイルを表示

  • availableMembers(ofFontFamily:) フォントファミリーから使用可能なメンバを取得
  • displayName  NSFontのインスタンスからローカライズされた名前を取得
フォントファミリーからさらに使用可能なメンバを表示するサンプル
let fontFamilies = NSFontManager.shared.availableFontFamilies
for family in fontFamilies {
    let localizedFamilyName = NSFontManager.shared.localizedName(forFamily: family, face: nil)
    print(localizedFamilyName)//フォントファミリー名

    //フォントファミリー名から使用可能なメンバを取得
    let FontMembers = NSFontManager.shared.availableMembers(ofFontFamily: family)
    for i in 0 ..< FontMembers!.count{
        let Font = FontMembers![i][0] as! String//ここで使用可能なメンバを取得
        let FontName = NSFont(name: Font, size: NSFont.systemFontSize)//NSFontのインスタンスを作成
        print(FontName?.displayName)
    }
}

説明

availableMembers(ofFontFamily:)

  • フォントファミリーを指定して、使用可能なフォントのメンバを取得する

For example, if you call availableMembersOfFontFamily:@"Times", it might return an array like this:
(("Times-Roman", "Roman", 5, 4),
("Times-Italic", "Italic", 6, 5),
("Times-Bold", "Bold", 9, 2),
("Times-BoldItalic", "Bold Italic", 9, 3)
)

AppleDocumentation / availablemembersより

.displayName

  • NSFontのインスタンスからローカライズされたフォント名を取得する

備考

全てのフォントファイルが完全であるとは限らないので本当は、エラー処理をする必要があるかも知れません。

何か間違っているところがあったら指摘願います。

参考

https://developer.apple.com/documentation/appkit/nsfontmanager
https://developer.apple.com/documentation/appkit/nsfont

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2