如何在 iOS 9 中使用新的 San Francisco 字体?

How to use new San Francisco font in iOS 9?

iOS 9 之前我们使用 fontWithName of UIFont:

来引用字体
[UIFont fontWithName:@"HelveticaNeue" size:18]

现在我们转向iOS 9. 如何以同样的方式引用新的San Francisco 字体

我们可以将它与 systemFontOfSizeUIFont 一起使用,但是如何引用常规样式以外的样式?例如,如何使用 San Francisco MediumSan Francisco Light 字体?

在iOS9中是系统字体,所以你可以这样做:

let font = UIFont.systemFontOfSize(18)

可以直接使用字体名称,但我认为这不安全:

let font = UIFont(name: ".SFUIText-Medium", size: 18)!

您还可以使用 specific weight 创建字体,如下所示:

let font = UIFont.systemFontOfSize(18, weight: UIFontWeightMedium)

let font = UIFont.systemFontOfSize(18, weight: UIFontWeightLight)

Swift 4

label.font = UIFont.systemFont(ofSize: 22, weight: UIFont.Weight.bold)

详情

  • Xcode 版本 10.2.1 (10E1001),Swift 5

解决方案

import UIKit

extension UIFont {

    enum Font: String {
        case SFUIText = "SFUIText"
        case SFUIDisplay = "SFUIDisplay"
    }

    private static func name(of weight: UIFont.Weight) -> String? {
        switch weight {
            case .ultraLight: return "UltraLight"
            case .thin: return "Thin"
            case .light: return "Light"
            case .regular: return nil
            case .medium: return "Medium"
            case .semibold: return "Semibold"
            case .bold: return "Bold"
            case .heavy: return "Heavy"
            case .black: return "Black"
            default: return nil
        }
    }

    convenience init?(font: Font, weight: UIFont.Weight, size: CGFloat) {
        var fontName = ".\(font.rawValue)"
        if let weightName = UIFont.name(of: weight) { fontName += "-\(weightName)" }
        self.init(name: fontName, size: size)
    }
}

用法

guard let font = UIFont(font: .SFUIText, weight: .light, size: 14) else { return }

// ...

let font = UIFont(font: .SFUIDisplay, weight: .bold, size: 17)!