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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31369711/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:50:17  来源:igfitidea点击:

How to use new San Francisco font in iOS 9?

iosfontsios9

提问by alexey

Before iOS 9to reference fonts we used fontWithNameof UIFont:

iOS 9之前我们使用fontWithName的引用字体UIFont

[UIFont fontWithName:@"HelveticaNeue" size:18]

Now we're moving to iOS 9. How to reference a new San Francisco fontin the same way?

现在我们要迁移到 iOS 9。如何以同样的方式引用新的San Francisco 字体

We can use it with systemFontOfSizeof UIFont, but how to reference styles other than regular? For example, how to use San Francisco Mediumor San Francisco Lightfonts?

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

回答by MirekE

In iOS 9 it is the system font, so you could do:

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

let font = UIFont.systemFontOfSize(18)

You canuse the font name directly, but I don't think this is safe:

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

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

You can also create the font with specific weight, like so:

您还可以创建具有特定 weight的字体,如下所示:

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

or

或者

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

回答by Marcos Dávalos

Swift 4

斯威夫特 4

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

回答by Vasily Bodnarchuk

Details

细节

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

Solution

解决方案

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)
    }
}

Usage

用法

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

// ...

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