簡體   English   中英

具有自定義大小的文本樣式的系統字體

[英]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

問題:

  • 有沒有辦法在上面的API中指定系統字體名稱? 如果是這樣,iOS 15 和 macOS Monterey 的字體名稱是什么?
  • 對於具有自定義大小的系統字體,還有其他方法可以實現動態 fonts 嗎?

沒有辦法做到這一點,但是我意識到預定義文本 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM