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)
我怎样才能缩短它,以便我可以用一个词左右完美地导入它?
您可以使用自定义视图修饰符。
\nstruct 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}\nRun Code Online (Sandbox Code Playgroud)\nText("How are you today? \xe2\x98\x80\xef\xb8\x8f")\n .modifier(TextModifier())\nRun Code Online (Sandbox Code Playgroud)\n如果您想要更简单的方法来使用修饰符,您可以在 View 上创建扩展,如下所示:
\nextension View {\n func textStyle() -> some View {\n modifier(TextModifier())\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n然后使用它:
\nText("How are you today? \xe2\x98\x80\xef\xb8\x8f")\n .textStyle()\nRun Code Online (Sandbox Code Playgroud)\n有关ViewModifiers和扩展的更多信息
\n希望这可以帮助 :)
\n