iOS13から使えるようになっていたカスタムフォントのAPIを試してみました。
この機能を使うと端末へのフォントインストールやフォントの確認ができます。
まずはフォント一覧の取得をしてみようと思います。 最初にテスト用のプロジェクトを作ります。
プロジェクトを作ったらプロジェクト設定の「Signing & Capabilities」でFontsを有効化します。
Storyboardで下のようにラベルとボタンだけ配置します。
最後にボタンを押したらUIFontPickerViewController(フォント一覧画面)を表示するような実装をします。
class ViewController: UIViewController { @IBAction func tapBtn() { let v = UIFontPickerViewController() present(v, animated: true, completion: nil) } }
アプリを起動してボタンを押すとフォント一覧を見る事ができました。
次に一覧からフォントを選んで使います。
コードは下のとおりです。
ViewControllerをUIFontPickerViewControllerDelegateに準拠させました。
class ViewController: UIViewController { @IBOutlet weak var testLabel: UILabel! @IBAction func tapBtn() { let v = UIFontPickerViewController() v.delegate = self present(v, animated: true, completion: nil) } } extension ViewController: UIFontPickerViewControllerDelegate { func fontPickerViewControllerDidPickFont(_ viewController: UIFontPickerViewController) { guard let fontDescriptor = viewController.selectedFontDescriptor else { return } testLabel.font = UIFont(descriptor: fontDescriptor, size: 17) } }
これでフォント選択したらラベルのフォントが変わるようになりました。
フォント一覧ですが、filteredLanguagesPredicateを使うと日本語対応フォントのみといった絞り込みができます。
let v = UIFontPickerViewController() v.configuration.filteredLanguagesPredicate = UIFontPickerViewController.Configuration.filterPredicate(forFilteredLanguages: ["js"])
次はフォントのインストールをしてみます。
フォントはNikkyou Sansというフォントを使わせて頂きました。
Nikkyou Sans Font | daredemotypo | FontSpace
ダウンロードしたフォントをxcassetsに追加します。
フォントのインストール処理は下のとおりです。
CTFontManagerRegisterFontsWithAssetNamesメソッドでxcassetsのフォントを登録できます。
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() CTFontManagerRegisterFontsWithAssetNames(["NikkyouSans-B6aV"] as CFArray, nil, .user, true, { arr, result in print(arr) print(result) return true }) } }
アプリを起動すると下のようにインストール確認画面が表示されます。
インストールしたフォントは下のようにフォント一覧画面で選べるようになります。