You can create a custom modifier to your View called ViewModifier
in SwiftUI.
You can customize the SwiftUI View for general purposes by using ViewModifier
.
This time, I will summarize such `View Modifier.
It is a protocol
to implement the function to customize and return the View by applying it to the View.
The functions defined in ViewModifier protocol
are:
func body(content: Self.Content) -> Self.Body
View is updated or converted in this function and returned.
content
is the proxy of the View to qualify.
Self.Body
is defined by ʻassociated type`, and the type of View to be returned to the conversion process of View is described here.
Let's create a custom Modifier to convert a simple View to a card-type View.
It's simple to do, create a custom Modifier struct, apply a value to the content
argument of thebody (content:)
and return it.
After that, apply the Modifier created using to the View you want to apply.
struct CardModifier: ViewModifier {
func body(content: Content) -> some View {
content
.padding(16)
.background(Color.white)
.cornerRadius(10)
.shadow(radius: 5)
}
}
struct ContentView: View {
var body: some View {
VStack {
// .modifier(_:)、 ModifiedContent(content:modifier:)Either is applicable.
Text("Hello, world!")
.modifier(CardModifier())
ModifiedContent(content: Text("Hello, world!"),
modifier: CardModifier())
}
}
}
Due to the above, the changes described in the custom Modifier will be applied to the corresponding View as follows.
By using ViewModifier
, you can define the layout to be applied to multiple views in general.
Since SwiftUI describes the layout in a method chain, readability will deteriorate if multiple same processes are lined up in solid writing when defining the same layout.
In order to keep the code clean, I think it is better to organize the views with the same layout with a custom modifier.
Recommended Posts