跳转至
Protocol

ViewModifier

A modifier that you apply to a view or another view modifier, producing a new view.

Declaration

protocol ViewModifier

Overview

Conform to the ViewModifier protocol when you want to create a reusable modifier that you can apply to any view. The example below combines several modifiers to create a new modifier that you can use to create blue caption text surrounded by a rounded rectangle:

struct BorderedCaption: ViewModifier {
    func body(content: Content) -> some View {
        content
            .font(.caption2)
            .padding(10)
            .overlay(
                RoundedRectangle(cornerRadius: 15)
                    .stroke(lineWidth: 1)
            )
            .foregroundColor(Color.blue)
    }
}

struct ExampleView: View {
    var body: some View {
        VStack {
            Text("Text without blue border")
            Text("Text with blue border")
                .modifier(BorderedCaption())
        }
    }
}
A screenshot displaying two lines of text in a VStack. A custom modifier applied directly to the view renders the second line in blue text surrounded by a rounded rectangle.

You can apply modifier(_:) directly to a view, but a more common and idiomatic approach uses modifier(_:) to define an extension to View itself that incorporates the view modifier:

extension View {
    func borderedCaption() -> some View {
        modifier(BorderedCaption())
    }
}
You can then apply the bordered caption to any view, similar to this:

struct BusView: View {
    var body: some View {
        Image(systemName: "bus")
            .resizable()
            .frame(width:50, height:50)
        Text("Downtown Bus")
            .borderedCaption()
    }
}
A screenshot showing the image of a bus with a caption reading Downtown Bus. A view extension, using a custom modifier, renders the caption in blue text surrounded by a rounded rectangle.

Note: The modifier(_:) only accepts a single modifier as a parameter. In order to use multiple modifiers on a single view, see concat(_:)

Availability

iOS 13.0+

macOS 10.15+

tvOS 13.0+

watchOS 6.0+

Topics


Type Alias

Content The content view type passed to body().


Associated Type

Body The type of view representing the body.


Instance Method

animation(_:) Returns a new version of the modifier that will apply Animation to all animatable values within the modifier.

body(content:) Gets the current body of the caller.

body(content:) Gets the current body of the caller.

concat(_:) Returns a new modifier that is the result of concatenating self with modifier.

transaction(_:) Returns a new version of the modifier that will apply the transaction mutation function transform to all transactions within the modifier.