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

Sky*_*erX 1 swiftui swiftui-text

我有一个经常使用的自定义字体修饰符,但是它使代码很长,因为我需要将其添加到多个位置。

这是修改器:

.font(.custom("Bebas Neue", size: 24)).foregroundStyle(LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom))
Run Code Online (Sandbox Code Playgroud)

我怎样才能缩短它,以便我可以用一个词左右完美地导入它?

Ori*_*Ori 5

您可以使用自定义视图修饰符。

\n

自定义修改器

\n
struct TextModifier: ViewModifier {\n    \n    let gradient = LinearGradient(gradient: Gradient(colors: [Color("lb"), Color("rb")]),startPoint: .top, endPoint: .bottom)\n    \n    func body(content: Content) -> some View {\n        content\n            .font(.custom("Bebas Neue", size: 24)).foregroundStyle(gradient)\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

用法

\n
Text("How are you today? \xe2\x98\x80\xef\xb8\x8f")\n    .modifier(TextModifier())\n
Run Code Online (Sandbox Code Playgroud)\n

额外(可选)

\n

如果您想要更简单的方法来使用修饰符,您可以在 View 上创建扩展,如下所示:

\n
extension View {\n    func textStyle() -> some View {\n        modifier(TextModifier())\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后使用它:

\n
Text("How are you today? \xe2\x98\x80\xef\xb8\x8f")\n    .textStyle()\n
Run Code Online (Sandbox Code Playgroud)\n
\n

有关ViewModifiers扩展的更多信息

\n

希望这可以帮助 :)

\n