在SwiftUI中创建ViewModifier和View扩展之间的区别 [英] Difference between creating ViewModifier and View extension in SwiftUI
问题描述
我正在尝试找出这两种方法之间的实际区别.例如:
I'm trying to find out what is practical difference between these two approaches. For example:
struct PrimaryLabel: ViewModifier {
func body(content: Content) -> some View {
content
.padding()
.background(Color.black)
.foregroundColor(Color.white)
.font(.largeTitle)
.cornerRadius(10)
}
}
extension View {
func makePrimaryLabel() -> some View {
self
.padding()
.background(Color.black)
.foregroundColor(Color.white)
.font(.largeTitle)
.cornerRadius(10)
}
}
然后我们可以通过以下方式使用所有这些对象:
Then we can use all of them following way:
Text(tech.title)
.modifier(PrimaryLabel())
Text(tech.title)
.makePrimaryLabel()
ModifiedContent(
content: Text(tech.title),
modifier: PrimaryLabel()
)
推荐答案
您提到的所有方法都是正确的.不同之处在于您如何使用它以及在何处访问它.哪个更好?是一个基于意见的问题,您应该查看简洁的代码策略和SOLID原则等,以找到每种情况下的最佳实践.
All of the approaches you mentioned are correct. The difference is how you use it and where you access it. Which one is better? is an opinion base question and you should take a look at clean code strategies and SOLID principles and etc to find what is the best practice for each case.
由于 SwiftUI
是非常修饰符链的基础,第二个选项是最接近原始修饰符的.您也可以接受诸如原始文件这样的参数:
Since SwiftUI
is very modifier chain base, The second option is the closest to the original modifiers. Also you can take arguments like the originals:
extension Text {
enum Kind {
case primary
case secondary
}
func style(_ kind: Kind) -> some View {
switch kind {
case .primary:
return self
.padding()
.background(Color.black)
.foregroundColor(Color.white)
.font(.largeTitle)
.cornerRadius(10)
case .secondary:
return self
.padding()
.background(Color.blue)
.foregroundColor(Color.red)
.font(.largeTitle)
.cornerRadius(20)
}
}
}
struct ContentView: View {
@State var kind = Text.Kind.primary
var body: some View {
VStack {
Text("Primary")
.style(kind)
Button(action: {
self.kind = .secondary
}) {
Text("Change me to secondary")
}
}
}
}
我们应该拭目以待,看看像这样的新技术中的 BEST 最佳实践.我们现在发现的任何东西都只是一种 GOOD 习惯.
We should wait and see what is the BEST practices in new technologies like this. Anything we find now is just a GOOD practice.
这篇关于在SwiftUI中创建ViewModifier和View扩展之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!