如何在iOS 9中使用新的旧金山字体?

时间:2015-07-12 15:57:25

标签: ios fonts ios9

iOS 9 之前我们使用fontWithName的{​​{1}}来引用字体:

UIFont

现在我们转向iOS 9.如何以相同的方式引用新的旧金山字体

我们可以将其与[UIFont fontWithName:@"HelveticaNeue" size:18] 的{​​{1}}一起使用,但如何引用常规以外的样式?例如,如何使用旧金山中等旧金山之光字体?

3 个答案:

答案 0 :(得分:113)

在iOS 9中,它是系统字体,因此您可以这样做:

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)

答案 1 :(得分:4)

Swift 4

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

答案 2 :(得分:0)

详细信息

  • 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)!