英文:
How to shorten long reusable modifiers like font style, foreground styles, etc
问题
我有一个自定义字体修改器,我经常使用它,但是由于我需要在多个地方添加它,所以代码变得很长。
这是修改器:
.font(.custom("Bebas Neue", size: 24)).foregroundStyle(LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]), startPoint: .top, endPoint: .bottom))
我该如何缩短它,以便最好只用一个单词或类似的方式导入它?
英文:
I have a custom font modifier that I am using often, however it makes the code very long as I need to add it in multiple places.
This is the modifier:
.font(.custom("Bebas Neue", size: 24)).foregroundStyle(LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom))
How can I shorten this so I can import it ideally with a single word or so?
答案1
得分: 4
你可以使用自定义视图修饰符。
自定义修饰符
struct TextModifier: ViewModifier {
let gradient = LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]), startPoint: .top, endPoint: .bottom)
func body(content: Content) -> some View {
content
.font(.custom("Bebas Neue", size: 24)).foregroundStyle(gradient)
}
}
用法
Text("How are you today? ☀️")
.modifier(TextModifier())
额外(可选)
如果你想要更容易地使用这个修饰符,你可以创建一个对视图的扩展,如下所示:
extension View {
func textStyle() -> some View {
modifier(TextModifier())
}
}
然后使用它:
Text("How are you today? ☀️")
.textStyle()
了解更多关于ViewModifiers和Extensions的信息。
英文:
You can use a custom view modifier.
Custom Modifier
struct TextModifier: ViewModifier {
let gradient = LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom)
func body(content: Content) -> some View {
content
.font(.custom("Bebas Neue", size: 24)).foregroundStyle(gradient)
}
}
Usage
Text("How are you today? ☀️")
.modifier(TextModifier())
Extra (optional)
If you want an easier way to use the modifer you can create an extension on View, like so:
extension View {
func textStyle() -> some View {
modifier(TextModifier())
}
}
Then to use it:
Text("How are you today? ☀️")
.textStyle()
More about ViewModifiers and Extensions
Hope this helps
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论