在 SwiftUI 中,我们如何重用一组修饰符或将它们变成一种组件来不重复调用它们? [英] In SwiftUI, how can we reuse a set of modifier or make them into a kind of component to not repeatedly call them?

查看:23
本文介绍了在 SwiftUI 中,我们如何重用一组修饰符或将它们变成一种组件来不重复调用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I know tons of people already thought about this, however I could't find any good answer on Stackoverflow or a good tutorial that purely talk about this even on some famous channels in Youtube.

我的问题很简单:

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

In SwiftUI we may do tons of time like this:

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

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

However, as you, or any other very experienced and professional developers may aware, we absolutely don't want to write .padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3)).background(Color.blue).cornerRadius(5) for every "Text(...)" or other like "Button" or any other SwiftUI component. we do want to wrap the .padding(EdgeInsets(top: 3, leading: 3, bottom: 3, trailing: 3)).background(Color.blue).cornerRadius(5) in some kind of methods or somewhere else. I know how to do it in UIKit, but the question is how do we do that since SwiftUI is a declarative way of build GUIs?

谢谢.

推荐答案

这里是通常如何使用自定义 ViewModifier 完成的,另外还描述了如何通过参数配置它的示例:

Here is how it is usually done with custom ViewModifier, plus depicts example of how it could be configured via parameters:

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

使用 Xcode 11.2、iOS 13.2 测试

Tested with Xcode 11.2, iOS 13.2

这篇关于在 SwiftUI 中,我们如何重用一组修饰符或将它们变成一种组件来不重复调用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆