首页 > 解决方案 > 这种类型的 SwiftUI 附加函数模式叫什么,我如何自己制作?

问题描述

在 SwiftUI 中,元素及其属性可以“附加”,如下所示:

Text("Hello World")
  .font(.body)
  .frame(maxWidth: 300, alignment: .leading)
  .padding(EdgeInsets(top: 0, leading: 0, bottom: 5, trailing: 0))

现在我想创建自己的,而不是写

.background(Rectangle().foregroundColor(Color.green))

每次我可以将它放入一个名为的函数中coloredDebugBackground(),然后将其“附加”到我想要着色的每个元素上,就像这样

Text("Hello World")
  .coloredDebugBackground()

我很确定那里有一些材料,但我不知道这种类型/模式/系统叫什么!

标签: iosswiftswiftui

解决方案


通常这被称为建造者模式。这里描述得很好:https ://www.swiftbysundell.com/articles/using-the-builder-pattern-in-swift/


推荐阅读