【问题标题】:Adding custom fonts as an extension to the Font type SwiftUI添加自定义字体作为字体类型 SwiftUI 的扩展
【发布时间】:2021-05-26 15:34:09
【问题描述】:

首先要明确的是,我不是在问如何将自定义字体添加到 SwiftUI,我是在问如何使用自定义字体扩展字体类型。

例如我使用自定义字体Manrope。我将 ttf 文件添加到我的项目中,并将其添加到我的信息 plist 中。目前我必须使用这样的字体:

.font(.custom("Manrope-SemiBold", size: 24))

我想知道我是否可以扩展字体以便我可以像这样使用 Manrope

.font(.manrope.semibold())

.font(.manrope("Semibold"))

【问题讨论】:

    标签: swift fonts swiftui


    【解决方案1】:

    为设置的自定义字体使用多种字体类型和函数的枚举。

    这是一个可能的解决方案

    //MARK: Font Extension
    extension Font {
        enum ManropeFont {
            case semibold
            case custom(String)
            
            var value: String {
                switch self {
                case .semibold:
                    return "Semibold"
                    
                case .custom(let name):
                    return name
                }
            }
        }
        
        enum RobotoFont {
            case semibold
            case custom(String)
            
            var value: String {
                switch self {
                case .semibold:
                    return "Semibold"
                    
                case .custom(let name):
                    return name
                }
            }
        }
        
        static func manrope(_ type: ManropeFont, size: CGFloat = 26) -> Font {
            return .custom(type.value, size: size)
        }
        
        static func roboto(_ type: RobotoFont, size: CGFloat = 26) -> Font {
            return .custom(type.value, size: size)
        }
    }
    

    用法

    struct ContentViewFonts: View {
        var body: some View {
            VStack {
                Text("Text demo")
                    .font(.manrope(.semibold))
                
                Text("Text demo")
                    .font(.roboto(.semibold))
                
                Text("Text demo")
                    .font(.roboto(.semibold, size: 10))
                
                Text("Text demo")
                    .font(.roboto(.custom("Bold")))
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      您可以将自定义字体声明为 Font 上的静态计算属性:

      extension Font {
          
          static var myCustomFont: Font {
              Font.custom("Manrope-SemiBold", size: 24)
          }
          
      }
      

      甚至更好地支持动态类型:

      extension Font {
      
          static var myCustomFont: Font {
              Font.custom("Manrope-SemiBold", size: 24, relativeTo: .title2)
          }
      }
      

      然后您可以像预定义系统字体一样使用它:

      Text("Example")
          .font(.myCustomFont)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 1970-01-01
        • 2013-07-14
        • 2010-09-26
        • 2021-05-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多