是否可以使用SwiftUI修饰符更改内容中的特定元素?

时间:2019-09-17 02:26:46

标签: swift swiftui

good article关于如何使用SwiftUI修改器来更改外观。但这将在全球范围内改变外观。这意味着它改变了所有样式。我想知道是否有一种方法可以使用类似的方法来仅更改内容中的特定元素?例如,我有一个组件 MyComponent ,其中包括一个文本和一个按钮。我想分别更改文本按钮的样式。

MyComponent.myTextStyle(...).myButtonStyle(...) 

1 个答案:

答案 0 :(得分:1)

您可以将修饰符应用于这样的视图实例:

struct ContentView: View {
    var body: some View { 
        Text("My text").modifier(PrimaryLabelStyle())
    }
}

您还可以拥有一个组件并将外部修饰符应用于该组件。

struct ContentView: View {
    var body: some View {
        MyComponent(textModifier: PrimaryLabelStyle(), buttonModifier: PrimaryButtonStyle())        
    }
}

struct MyComponent<T,U>: View where T:ViewModifier, U:ViewModifier{
    let textModifier:T
    let buttonModifier:U
    var body: some View {
        VStack {
            Text("My Text")
                .modifier(textModifier)
            Button(action:{}){
                Text("My Button")
            }.modifier(buttonModifier)
        }

    }
}

struct PrimaryLabelStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(Color.red)
            .foregroundColor(Color.white)
            .font(.largeTitle)
    }
}

struct PrimaryButtonStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .padding()
            .background(Color.yellow)
            .foregroundColor(Color.white)
            .font(.largeTitle)
    }
}

enter image description here