[英]Adding custom fonts as an extension to the Font type SwiftUI
First to be clear, I am not asking how can I add custom fonts to SwiftUI, I'm asking how can I extend the Font type with custom fonts.首先要清楚,我不是问如何将自定义 fonts 添加到 SwiftUI,我问如何使用自定义 Z980D14C0C85495B48B9A9134658E6121 扩展字体类型。
For example I am using the custom font Manrope .例如,我正在使用自定义字体Manrope 。 I added the ttf files to my project and added it to my Information plist.
我将 ttf 文件添加到我的项目中,并将其添加到我的信息 plist 中。 Current I have to use the font like this:
当前我必须使用这样的字体:
.font(.custom("Manrope-SemiBold", size: 24))
I was wondering if I could extend Font so that I could use Manrope like this我想知道我是否可以扩展字体以便我可以像这样使用 Manrope
.font(.manrope.semibold())
or或者
.font(.manrope("Semibold"))
Use enums for multiple font types and functions for the set custom font.为设置的自定义字体使用多种字体类型和函数的枚举。
Here is a possible solution这是一个可能的解决方案
//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)
}
}
Usage用法
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")))
}
}
}
You could declare your custom font as a static computed property on Font:您可以将自定义字体声明为字体上的 static 计算属性:
extension Font {
static var myCustomFont: Font {
Font.custom("Manrope-SemiBold", size: 24)
}
}
or even better like this to support dynamic type:甚至更好地支持动态类型:
extension Font {
static var myCustomFont: Font {
Font.custom("Manrope-SemiBold", size: 24, relativeTo: .title2)
}
}
Then you can use it the same way you would predefined system fonts:然后您可以像预定义系统 fonts 一样使用它:
Text("Example")
.font(.myCustomFont)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.