しめ鯖日記

swift, iPhoneアプリ開発, ruby on rails等のTipsや入門記事書いてます

iOS13のカスタムフォントを試してみる

iOS13から使えるようになっていたカスタムフォントのAPIを試してみました。
この機能を使うと端末へのフォントインストールやフォントの確認ができます。

まずはフォント一覧の取得をしてみようと思います。 最初にテスト用のプロジェクトを作ります。

f:id:llcc:20201031141030p:plain

プロジェクトを作ったらプロジェクト設定の「Signing & Capabilities」でFontsを有効化します。

f:id:llcc:20201031141015p:plain

Storyboardで下のようにラベルとボタンだけ配置します。

f:id:llcc:20201031142117p:plain

最後にボタンを押したらUIFontPickerViewController(フォント一覧画面)を表示するような実装をします。

class ViewController: UIViewController {
    @IBAction func tapBtn() {
        let v = UIFontPickerViewController()
        present(v, animated: true, completion: nil)
    }
}

アプリを起動してボタンを押すとフォント一覧を見る事ができました。

f:id:llcc:20201031143020p:plain

次に一覧からフォントを選んで使います。
コードは下のとおりです。
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)
    }
}

これでフォント選択したらラベルのフォントが変わるようになりました。

f:id:llcc:20201031143619p:plain

フォント一覧ですが、filteredLanguagesPredicateを使うと日本語対応フォントのみといった絞り込みができます。

let v = UIFontPickerViewController()
v.configuration.filteredLanguagesPredicate = UIFontPickerViewController.Configuration.filterPredicate(forFilteredLanguages: ["js"])

次はフォントのインストールをしてみます。
フォントはNikkyou Sansというフォントを使わせて頂きました。

Nikkyou Sans Font | daredemotypo | FontSpace

ダウンロードしたフォントをxcassetsに追加します。

f:id:llcc:20201031151439p:plain

フォントのインストール処理は下のとおりです。
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
        })
    }
}

アプリを起動すると下のようにインストール確認画面が表示されます。

f:id:llcc:20201031151602p:plain

インストールしたフォントは下のようにフォント一覧画面で選べるようになります。

f:id:llcc:20201031151713p:plain