如何在SwiftUI中使用SF圆角字体?

643ylb08  于 2023-05-21  发布在  Swift
关注(0)|答案(6)|浏览(149)

我尝试在SwiftUI项目中使用SF圆角字体,您会如何设置它?
我已经尝试过使用.font(),但它不起作用(我无法将其设置为圆形字体)

7gs2gvoe

7gs2gvoe1#

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

2o7dmzc52#

我知道这个问题是关于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
}
vuv7lop3

vuv7lop33#

这样做对我来说在SwiftUI中的Text对象上是有效的:
.font(.system(size: 13.0, weight: .regular, design: .rounded))

ej83mcc0

ej83mcc04#

将@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)
    }
}
q3qa4bjr

q3qa4bjr5#

我想添加一个额外的用例:如果您希望在保持动态字体缩放的同时,将自定义字体粗细应用于文本字段等四舍五入的SF字体,可以执行以下操作:

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

这是必需的,因为用户不能直接在TextField上调用.fontWeight()(至少从iOS 13开始)。

z18hc3ub

z18hc3ub6#

iOS 16.1

使用fontDesign(.rounded)

Text("Hello, World!")
    .fontDesign(.rounded)

相关问题