SwiftUI 简明教程之字体

本文为 Eul 样章,如果您喜欢,请移步 AppStore/Eul 查看更多内容。

Eul 是一款 SwiftUI & Combine 教程 App(iOS、macOS),以文章(文字、图片、代码)配合真机示例(Xcode 12+、iOS 14+,macOS 11+)的形式呈现给读者。笔者意在尽可能使用简洁明了的语言阐述 SwiftUI & Combine 相关的知识,使读者能快速掌握并在 iOS 开发中实践。

系统内置字体

SwiftUI 中的字体,具有动态缩放的特性:

  • 在不同设备上会动态缩放
  • 在支持动态类型的 App 中,能根据手机设置的字体大小动态缩放

字体的调用:

Text("Stay Hungry, Stay Foolish!").font(.largeTitle)


自定义字体

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

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

  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

这里顺便提一下这个属性修饰器,它的定义和初始化方法如下:

@propertyWrapper struct ScaledMetric<Value> where Value : BinaryFloatingPoint

init(wrappedValue: Value)
// Creates the scaled metric with an unscaled value using the default scaling.

init(wrappedValue: Value, relativeTo: Font.TextStyle)
// Creates the scaled metric with an unscaled value and a text style to scale relative to.

从中我们得知,它只能修饰浮点类型的数据。它的作用是什么呢,就是根据系统设置的字体大小,动态地改变浮点类型的值大小。

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

@ScaledMetric(relativeTo: .title) var imgSize: CGFloat = 150

本文为 Eul 样章,如果您喜欢,请移步 AppStore/Eul 查看更多内容。

posted @ 2021-04-16 16:51  Bruce2077  阅读(1520)  评论(0编辑  收藏  举报