如何在SwiftUI中使用SF Rounded字体?

19

我正在尝试在我的SwiftUI项目中使用SF圆体字体,你该如何设置?

我已经尝试过修改.font(),但是没有成功(我无法将它设置为这种圆体字体)。


1
如何在不使用SwiftUI的情况下进行设置? - Marvin Ruciński
@MarvinRuciński 在iOS 13中有一个名为UIFontDescriptor.SystemDesign的新的UIKit API。 - Jonny
6个回答

57
Text("Your Text").font(.system(.body, design: .rounded))

45

我知道这个问题是关于SwiftUI的,但我认为也包括一个UIKit的答案可能会有所帮助。

let fontSize: CGFloat = 24

// Here we get San Francisco with the desired weight
let systemFont = UIFont.systemFont(ofSize: fontSize, weight: .regular)

// Will be SF Compact or standard SF in case of failure.
let font: UIFont

if let descriptor = systemFont.fontDescriptor.withDesign(.rounded) {
    font = UIFont(descriptor: descriptor, size: fontSize)
} else {
    font = systemFont
}

11

SwiftUI中,这种做法对Text对象有效:

.font(.system(size: 13.0, weight: .regular, design: .rounded))


8

我觉得需要增加一个额外的使用场景:如果您想在类似文本字段的元素上应用自定义字重以及同时保持动态字体缩放,您可以按照以下步骤操作:

TextField("test", $test)
    .font(Font.system(.largeTitle, design: .rounded).weight(.heavy))

这是必需的,因为在iOS 13版中,不能直接在TextField上调用.fontWeight()方法。


8
将 @Pomme2Poule 的 UIKit 答案转换为函数以便于使用,如果有需要的话。函数还使用了动态类型,因此它会随着字体大小而调整大小。
func roundedFont(ofSize style: UIFont.TextStyle, weight: UIFont.Weight) -> UIFont {
    // Will be SF Compact or standard SF in case of failure.
    let fontSize = UIFont.preferredFont(forTextStyle: style).pointSize
    if let descriptor = UIFont.systemFont(ofSize: fontSize, weight: weight).fontDescriptor.withDesign(.rounded) {
        return UIFont(descriptor: descriptor, size: fontSize)
    } else {
        return UIFont.preferredFont(forTextStyle: style)
    }
}

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接