Font AwesomeのダウンロードページからDownload Free for Desktopをクリックし、ダウンロードしたZIPファイルを展開します。
ファイル名にスペースがあると何故かXcodeで反映されなかったので、ファイル名のスペースをアンダーバーに変更しておきます。
Font Awesome 7 Brands-Regular-400.otf → Font Awesome 7 Brands-Regular-400.otf
Font Awesome 7 Free-Regular-400.otf → Font_Awesome_7_Free-Regular-400.otf
Font Awesome 7 Free-Solid-900.otf → Font_Awesome_7_Free-Solid-900.otf
Xcodeのプロジェクトナビゲーター(左側のファイルが表示されているタブ)にファイルをドロップします。そしてInfo.plistに以下を追加します。
<key>UIAppFonts</key>
<array>
<string>Font_Awesome_7_Brands-Regular-400.otf</string>
<string>Font_Awesome_7_Free-Regular-400.otf</string>
<string>Font_Awesome_7_Free-Solid-900.otf</string>
</array>
これでFont Awesomeが使えるようになりました。構造体化して簡単に使いまわせるようにしましょう。
TextにFont Awesomeのコードポイントを入れ、フォントに先ほど追加したフォントのファミリー名を指定します。
Brands(企業ロゴ)を使う場合はfontWeightを.mediumに、Solid(通常のアイコン)を使う場合は.blackを指定します。この構造体ではbrandの真偽で設定しています。
import SwiftUI
struct Symbol: View {
@State var width:CGFloat = 23.0
@State var systemName:String?
@State var awesome:String?
@State var brand:Bool?
var body: some View {
ZStack(alignment:.center) {
Spacer()
.frame(width:width)
if systemName != nil {
Image(systemName:systemName ?? "")
} else if awesome != nil {
FontAwesome(code: awesome ?? "", size:16, brand:brand)
.multilineTextAlignment(.center)
}
}
.frame(width:width)
.clipped()
}
}
struct FontAwesome: View {
@State var code:String
@State var size:CGFloat?
@State var brand:Bool?
var body: some View {
if let scalar = UnicodeScalar(Int(code, radix: 16) ?? 0)
{
Text(String(scalar))
.font(.custom(brand ?? false ? "Font Awesome 7 Brands":"Font Awesome 7 Free", size: size ?? 16))
.fontWeight(brand ?? false ? .medium:.black)
} else {
Text("")
}
}
}
コードポイントはFont Awesomeの記号を検索した画面の右上に、f099のように書かれている文字です。BrandかはHTMLのコードに fa-brands があるかを確認すれば判別できます。
出力される記号はText構造体であるため、.foregroundなどを利用することができます。