SwiftUI - 字体

1,040 阅读1分钟

内置字体

Text("Swift UI")
            .font(.system(.title))   // 系统提供的字体大小
            .font(.system(.title2, design: .monospaced))
            .font(.system(size: 40, weight: .heavy, design: .rounded))  // 大小、字重、风格
            .fontWeight(.regular) // 字重
            .bold()  // 加粗
            .italic()  // 斜体
            .font(.body.leading(.loose)) // 间距变大
            .font(.body.leading(.standard)) // 间距默认
            .font(.body.leading(.tight)) // 间距变小

自定义字体

1.添加字体文件 ( Legends.otf ) 至工程

2.在 Info.plist 中配置相应的字体

截屏2022-12-08 下午3.54.36.png

3.通过以下方法调用自定义字体

// 根据设备设置的字体动态缩放,默认以 .body 大小为参考值放大或缩小 
public static func custom(_ name: String, size: CGFloat) -> Font 

// 根据设备设置的字体动态缩放,参考值可自定义(relativeTo) 
public static func custom(_ name: String, size: CGFloat, relativeTo textStyle: Font.TextStyle) -> Font 

// 固定字体大小 
public static func custom(_ name: String, fixedSize: CGFloat) -> Font

ScaledMetric

属性修饰器, 可以动态的改变图片和文字的大小

比如,一个图片大小是 150 x 150,如果我们不动态地缩放,它在任何系统设置的字体大小下,都是该尺寸,如果我们将他的宽高通过如下代码设置为动态值,它就可以动态的缩放了。

// 以title 为参照
@ScaledMetric(relativeTo: .title) var imgSize: CGFloat = 150