iOS 內建了上百款字型,但要用就得知道它「真正的名稱」——這個名稱往往和你在字型選單裡看到的不一樣。系統提供了 [UIFont familyNames] 可以一次列出所有可用字型家族。
[UIFont fontWithName:(NSString *)fontName size:(CGFloat)fontSize];
// 遍歷字型名稱
for (NSString *str in [UIFont familyNames]) {
dlog(@"UIFont_name: %@", str);
}
執行後會在 console 印出一份清單,節錄部分如下:
UIFont_name: Marion UIFont_name: Copperplate UIFont_name: Heiti SC UIFont_name: Iowan Old Style UIFont_name: Courier New UIFont_name: Apple SD Gothic Neo UIFont_name: Heiti TC UIFont_name: Gill Sans UIFont_name: Marker Felt UIFont_name: Thonburi UIFont_name: Avenir Next Condensed UIFont_name: Helvetica Neue UIFont_name: Times New Roman UIFont_name: Georgia UIFont_name: Apple Color Emoji UIFont_name: Arial Rounded MT Bold UIFont_name: Chalkboard SE UIFont_name: Superclarendon UIFont_name: Damascus UIFont_name: Noteworthy UIFont_name: Geeza Pro UIFont_name: Avenir UIFont_name: Academy Engraved LET UIFont_name: Mishafi UIFont_name: Futura UIFont_name: Farah UIFont_name: Arial Hebrew UIFont_name: Arial UIFont_name: Party LET UIFont_name: Chalkduster UIFont_name: Hiragino Kaku Gothic ProN UIFont_name: Hoefler Text UIFont_name: Optima UIFont_name: Palatino UIFont_name: Al Nile UIFont_name: Bradley Hand UIFont_name: Hiragino Mincho ProN UIFont_name: Trebuchet MS UIFont_name: Helvetica UIFont_name: Courier UIFont_name: Cochin UIFont_name: Snell Roundhand UIFont_name: Zapf Dingbats UIFont_name: Bodoni 72 UIFont_name: Verdana UIFont_name: American Typewriter UIFont_name: Avenir Next UIFont_name: Baskerville UIFont_name: Didot UIFont_name: Savoye LET UIFont_name: Bodoni Ornaments UIFont_name: Symbol UIFont_name: Menlo UIFont_name: Bodoni 72 Smallcaps UIFont_name: DIN Alternate UIFont_name: Papyrus UIFont_name: Euphemia UCAS UIFont_name: Zapfino UIFont_name: Bodoni 72 Oldstyle UIFont_name: DIN Condensed

這份清單會隨 iOS 版本增減,因此不要把名稱寫死在程式碼裡不做驗證。較穩妥的寫法是先建立物件再判斷是否為 nil,若為 nil 就退回系統字型:
UIFont *font = [UIFont fontWithName:@"DIN Alternate" size:18.0];
if (!font) {
font = [UIFont systemFontOfSize:18.0];
}
label.font = font;
另外要注意兩點:其一,fontWithName: 對英數與符號有效,但中文字型的處理一直是弱項,中文環境請改用 systemFontOfSize: 或 preferredFontForTextStyle:(後者還能自動響應使用者的動態字型設定)。其二,若要使用專案自帶的第三方字型檔,必須先把 ttf/otf 加入 target,並在 Info.plist 的 UIAppFonts 陣列中登記檔名,否則 fontWithName: 永遠取不到。