CustomDynamicType - 在 iOS 中桥接自定义字体和辅助功能

Version License Swift Compatibility Platform Compatibility

Banner

简介

欢迎使用 CustomDynamicType,这是一个多功能的 Swift 库,旨在将自定义字体无缝集成到 iOS Dynamic Type 中。这个库不仅仅是使用个性化字体来增强应用程序美观度的一种手段,更是一种对包容性的承诺。

此解决方案专为 UIKit 和 SwiftUI 量身定制,可在不同的 iOS 开发环境中提供流畅且适应性强的体验。

借助 CustomDynamicType,您现在可以确保您的自定义字体完全支持并包含 Apple 广泛的辅助功能。

无论您是构建新的应用程序还是改进现有的应用程序,CustomDynamicType 都是您创建更易于访问且更具视觉吸引力的 iOS 应用程序的途径。加入我们,重新定义 iOS 生态系统中设计和辅助功能的边界。

用法

将 CustomDynamicType 集成到您的 iOS 应用程序中非常简单,您可以一边使用自定义字体,一边完全支持辅助功能。 请按照以下步骤进行设置

步骤 1:定义您的自定义字体

首先,定义应用程序的自定义字体。 CustomDynamicType 支持各种字体粗细

确保这些字体包含在您的项目中并在应用程序的 Info.plist 中配置。如果是第一次集成自定义字体,请遵循 Apple 文档

步骤 2:初始化 CustomDynamicType

在您的 AppDelegate 的 application(_:didFinishLaunchingWithOptions:) 方法中,初始化 CustomDynamicType

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
    let fontNames = CustomDynamicFontNames(
        ultraLight: "YourFontName-UltraLight",
        thin: "YourFontName-Thin",
        light: "YourFontName-Light",
        regular: "YourFontName-Regular", // Required
        medium: "YourFontName-Medium",
        semibold: "YourFontName-SemiBold", // Required
        bold: "YourFontName-Bold",
        heavy: "YourFontName-Heavy",
        black: "YourFontName-Black"
    )
    CustomDynamicType.setup(with: fontNames)
    
    return true
}

"YourFontName" 替换为您实际的字体名称。 regularsemibold 是必需的,因为 Apple 默认实现依赖于这些粗细,其他的是可选的。

UIKit 集成

轻松将自定义字体应用于 UILabels。 示例

let label = UILabel()
label.setFont(style: .largeTitle)

let boldLabel = UILabel()
boldLabel.setFont(style: .body, overrideWeight: .bold)

在这些示例中,setFont(style:overrideWeight:) 用于将所需的字体样式应用于每个 UILabel。 overrideWeight 参数是可选的,并支持 UIFont.Weight 的任何变体(ultraLightthinlightregularmediumsemiboldboldheavyblack),但请记住,您需要使用相应的字体名称设置库,否则它将回退到常规字体。

SwiftUI 集成

将自定义字体应用于 SwiftUI 中的 Text 视图。 示例

Text("Title text")
    .font(Font.font(style: .largeTitle))
Text("Another text but for the body")
    .font(Font.font(style: .body, overrideWeight: .bold))

在 SwiftUI 中,您可以使用 Font.font(style:overrideWeight:) 为您的 Text 视图设置字体样式和可选粗细。 overrideWeight 参数是可选的,并支持 Font.Weight 的任何变体(ultraLightthinlightregularmediumsemiboldboldheavyblack),但请记住,您需要使用相应的字体名称设置库,否则它将回退到常规字体。

通过将这些方法合并到您的 iOS 应用程序中,您可以跨 UIKit 和 SwiftUI 平台保持一致且易于访问的字体样式。 CustomDynamicType 确保您的自定义字体不仅具有视觉吸引力,而且与 Apple 的辅助功能完全兼容。

Animation

文档

完整的文档可在 此链接 获取

安装

Swift Package Manager

将依赖项添加到 Package.swift 文件。

  dependencies: [
    .package(url: "https://github.com/neobeppe/CustomDynamicType.git", .upToNextMajor(from: "1.0.0"))
  ]

CocoaPods

CustomDynamicType 可通过 CocoaPods 获得。 要安装它,只需将以下行添加到您的 Podfile 中

pod 'CustomDynamicType'

许可证

CustomDynamicType 在 MIT 许可证下可用。 有关更多信息,请参见 LICENSE 文件。