添加自定义字体作为字体类型 SwiftUI 的扩展 [英] Adding custom fonts as an extension to the Font type SwiftUI
本文介绍了添加自定义字体作为字体类型 SwiftUI 的扩展的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先要明确,我不是在问如何将自定义字体添加到 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.
例如,我使用的是自定义字体 Manrope.我将 ttf 文件添加到我的项目并将其添加到我的信息 plist.目前我必须使用这样的字体:
For example I am using the custom font Manrope. I added the ttf files to my project and added it to my Information plist. Current I have to use the font like this:
.font(.custom("Manrope-SemiBold", size: 24))
我想知道是否可以扩展 Font 以便我可以像这样使用 Manrope
I was wondering if I could extend Font so that I could use Manrope like this
.font(.manrope.semibold())
或
.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)
}
}
用法
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")))
}
}
}
这篇关于添加自定义字体作为字体类型 SwiftUI 的扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文