本文為 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)
自定義字體
-
添加字體文件 ( Legends.otf ) 至工程
-
在 Info.plist 中配置相應的字體
-
通過以下方法調用自定義字體
// 根據設備設置的字體動態縮放,默認以 .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 查看更多內容。