如何缩短长的可重用修饰符,如字体样式、前景样式等

huangapple go评论70阅读模式
英文:

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()

了解更多关于ViewModifiersExtensions的信息。

英文:

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 如何缩短长的可重用修饰符,如字体样式、前景样式等

huangapple
  • 本文由 发表于 2023年3月3日 20:20:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/75627006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定