相关疑难解决方法(0)

在SwiftUI中创建ViewModifier和View扩展之间的区别

我试图找出这两种方法之间的实际区别。例如:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我们可以按以下方式使用所有这些:

Text(tech.title)
    .modifier(PrimaryLabel())
Text(tech.title)
    .makePrimaryLabel()
ModifiedContent(
    content: Text(tech.title),
    modifier: PrimaryLabel()
)
Run Code Online (Sandbox Code Playgroud)

ios swift swiftui

3
推荐指数
4
解决办法
307
查看次数

标签 统计

ios ×1

swift ×1

swiftui ×1