top of page
Writer's pictureHui Wang

40. SwiftUI: Introducing ViewModifier

Today I will show you how to use ViewModifier.


The ViewModifier is similar to CSS in web design, and is mainly used to integrate a set of commonly used view styles.


When there are many views with the same style in the project, we only need to apply a unified ViewModifier.


Steps:

  • First, let's import three images.


  • Adds an Image with the specified name and sets its width and height.

  • Sets the rounded corners of the Image, converting it to a circular shape.

  • Next, set the image saturation to 0 to convert the Image to a grayscale image.

  • Finally, increase the brightness of the Image by 0.1.

Image("beach")
    .resizable()
    .frame(width: 200, height: 200)
    .cornerRadius(100)
    .saturation(0)
    .brightness(0.1)

Add two more images and apply the same styles to them as the first Image.

  • To avoid repetition of work, we can create a ViewModifier.

  • Implement the body method in the ViewModifier protocol and return an Image.

  • Copy the style of the first Image to the body method.

struct ImageStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .frame(width: 200, height: 200)
            .cornerRadius(100)
            .saturation(0)
            .brightness(0.1)
    }
}

  • Embed the first Image into VStack.


  • Next, we apply this ViewModifier to the first Image.

  • Then add a second Image, and apply the same styles.

  • Finally, in the same way, add a third Image.

  • These three images have the same modifier. Therefore, if you need to modify the styles of these three images, you only need to modify the code in the ViewModifier.

VStack {
    Image("beach")
        .resizable()
        .modifier(ImageStyle())
    Image("mountain")
        .resizable()
        .modifier(ImageStyle())
    Image("squirrel")
        .resizable()
        .modifier(ImageStyle())
}

Source Code:

import SwiftUI

struct ContentView: View {
    
    var body: some View {
        VStack {
            Image("beach")
                .resizable()
                .modifier(ImageStyle())
            Image("mountain")
                .resizable()
                .modifier(ImageStyle())
            Image("squirrel")
                .resizable()
                .modifier(ImageStyle())
        }
    }
}

struct ImageStyle: ViewModifier {
    func body(content: Content) -> some View {
        content
            .frame(width: 200, height: 200)
            .cornerRadius(100)
            .saturation(0)
            .brightness(0.1)
    }
}

 

Follow me on:

Comentários


bottom of page