在 SwiftUI 中,我们如何重用一组修饰符或将它们变成一种组件来不重复调用它们?

Inv*_*ain 5 ios swiftui

我知道很多人已经考虑过这个问题,但是我在 Stackoverflow 上找不到任何好的答案,或者即使在 Youtube 的一些著名频道上也找不到纯粹谈论这个的好的教程。

我的问题很简单:

在 SwiftUI 中,我们可能会做很多这样的事情:

Text("Hello World")
  .padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3))
  .background(Color.blue)
  .cornerRadius(5)
Run Code Online (Sandbox Code Playgroud)

但是,正如您或任何其他非常有经验和专业的开发人员可能知道的那样,我们绝对不想.padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3)).background(Color.blue).cornerRadius(5)为每个“Text(...)”或其他类似“Button”或任何其他 SwiftUI 组件编写代码。我们确实想将 包装.padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3)).background(Color.blue).cornerRadius(5) 在某种方法或其他地方。我知道如何在 UIKit 中做到这一点,但问题是我们如何做到这一点,因为 SwiftUI 是一种构建 GUI 的声明性方式?

谢谢。

Asp*_*eri 17

以下是通常使用 custom 完成的方式ViewModifier,并描述了如何通过参数进行配置的示例:

struct MyTextModifier: ViewModifier {
    let corner: CGFloat
    func body(content: Content) -> some View {
        content
            .padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3))
            .background(Color.blue)
            .cornerRadius(corner)
    }
}

extension View {
    func configured(with radius: CGFloat = 5) -> some View {
        self.modifier(MyTextModifier(corner: radius))
    }
}

struct MyTextModifier_Previews: PreviewProvider {
    static var previews: some View {
        Text("Hello World")
            .configured()
    }
}
Run Code Online (Sandbox Code Playgroud)

使用 Xcode 11.2、iOS 13.2 进行测试


LuL*_*aGa 12

对修饰符进行分组以供重用的最简单方法是在 的扩展中声明它们View

extension View {

    func customStyle() -> some View {
        self.padding(3)
            .background(Color.blue)
            .cornerRadius(5)
    }
}
Run Code Online (Sandbox Code Playgroud)

那么你可以像这样简单地使用它:

Text("Hello World").customStyle()
Run Code Online (Sandbox Code Playgroud)

仅当所有修饰符都可以应用于视图时,这才有效。当您想要对特定于Image您的修饰符进行分组时,必须在Image等扩展中执行此操作。


dot*_*ot3 5

我会将每个组件创建为视图,而不是扩展。这样您就可以随时预览组件并拥有“可重用”组件的中央存储库:

struct customText : View {

 let text: String

 var body: some View {

  Text(string)
   .padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3))
   .background(Color.blue)
   .cornerRadius(5)
  }
}
Run Code Online (Sandbox Code Playgroud)

在上面附加预览,您始终可以准确地查看文本在预览画布中的外观,从而使将来的编辑更加容易。

并使用:

customText(text: "Hello World")
Run Code Online (Sandbox Code Playgroud)

您仍然可以为其使用添加修饰符。然后,您可以拥有可在整个应用程序中使用的单一视图源(不同的文本类型、按钮等)。