Swift添加字体到项目中
1. 下载字体,导入到项目文件夹。
2. 项目Info添加Fonts provided by application的item为字体文件名"xxx.ttf"。
3. 打印出所有字体名,找到导入的字体文件对应不同weight的字体。如果还是找不到,我也不知道怎么解决。
for family in UIFont.familyNames.sorted() {for fontName in UIFont.fontNames(forFamilyName: family).sorted() {print(fontName)}}4. 针对不同weight返回不同字体。
func getEnglishFont(ofSize size: CGFloat, weight: UIFont.Weight) -> UIFont {var font: UIFont? = nilswitch weight {case .ultraLight:font = UIFont(name: "KumbhSans-Regular_ExtraLight", size: size)case .thin:font = UIFont(name: "KumbhSans-KumbhSans-Regular_Thin", size: size)case .light:font = UIFont(name: "KumbhSans-Regular_Light", size: size)case .regular:font = UIFont(name: "KumbhSans-Regular", size: size)case .medium:font = UIFont(name: "KumbhSans-Regular_Medium", size: size)case .semibold:font = UIFont(name: "KumbhSans-Regular_SemiBold", size: size)case .bold:font = UIFont(name: "KumbhSans-Regular_Bold", size: size)case .heavy:font = UIFont(name: "KumbhSans-Regular_ExtraBold", size: size)case .black:font = UIFont(name: "KumbhSans-Regular_Black", size: size)default:print("default font")font = UIFont(name: "KumbhSans-Regular", size: size)}var nonEmptyFont: UIFont = UIFont.systemFont(ofSize: size, weight: weight)if let tmpFont = font {nonEmptyFont = tmpFont} else {print("使用默认字体")}return nonEmptyFont}