[英]System Font with custom size for text style
我想知道如何在我的SwiftUI
應用程序中使用支持動態大小的自定義大小的系統字體(當用戶更改設備上的文本大小時,字體大小會動態變化)。
我可以為系統 fonts 使用標准的.body
、 .title
等,但是我想使用稍微不同的自定義大小,但仍然想確保它適用於動態類型
//Font size doesn't change when the user changes his preferred text size on the device
Text("hello")
.font(.system(size: 14, weight: .bold, design: .default))
我的目標是iOS 15
,我正在尋找以下系統字體的內容:
static func custom(_ name: String, size: CGFloat, relativeTo textStyle: Font.TextStyle) -> Font
沒有辦法做到這一點,但是我意識到預定義文本 styles 之一符合要求。
有一種方法可以將字體修飾符鏈接在一起(設置像bold()
這樣的字體)
.font(.body.bold())
我根據當前sizeCategory
進行了一些 hacky 字體大小估計:
public enum AppTextStyle {
case veryCustomTextStyle
case anotherCustomTextStyle
}
struct ScaledFontModifier: ViewModifier {
@Environment(\.sizeCategory) var sizeCategory
var textStyle: AppTextStyle
func body(content: Content) -> some View {
content.font(font(for: textStyle))
}
private func font(for style: AppTextStyle) -> Font {
switch style {
case .veryCustomTextStyle:
return .system(size: scaledValue(for: 42))
case .anotherCustomTextStyle:
return .system(size: scaledValue(for: 42), weight: .medium)
}
}
private func scaledValue(for size: CGFloat) -> CGFloat {
switch sizeCategory {
case .extraSmall:
return size - 3
case .small:
return size - 2
case .medium:
return size - 1
case .large:
return size
case .extraLarge:
return size + 2
case .extraExtraLarge:
return size + 4
case .extraExtraExtraLarge:
return size + 6
case .accessibilityMedium:
return size + 11
case .accessibilityLarge:
return size + 16
case .accessibilityExtraLarge:
return size + 23
case .accessibilityExtraExtraLarge:
return size + 30
case .accessibilityExtraExtraExtraLarge:
return size + 36
@unknown default:
return size
}
}
}
public extension View {
func font(_ textStyle: AppTextStyle) -> some View {
modifier(ScaledFontModifier(textStyle: textStyle))
}
}
你可以沿着內置的 fonts 使用它,或者你可以把你所有的應用文本 styles 放在AppTextStyle
枚舉中:
Text("Hello")
.font(.body)
Text("World")
.font(.veryCustomTextStyle)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.