ViewModifier

Christine_Yang's avatar
Published Dec 9, 2022Updated Mar 2, 2023
Contribute to Docs

A ViewModifier is a protocol that can be called on a particular view. Modifier methods adhere to the protocol and return a new, altered View that will replace the originally created View.

Syntax

struct MyView: View {
    var body: some View {
        View(s) here
            Modifier methods like .bold() can be called underneath a View.
            Multiple modifiers can be chained using dot notation.
    }
}

Example

The following example displays some text:

import SwiftUI
struct ContentView: View {
var name: String = "Sam"
var body: some View {
Text("Hello \(name)")
.font(.title)
.bold()
}
}

In the example above, the .font() and .bold() modifiers are called on a Text view. In addition, a built-in text style, .title property, is passed into the .font() modifier.

This will display:

SwiftUI Modifier

ViewModifier

.animation()
Applies an animation to a view.
.background()
Applies a background to a view, which can be customized depending on the provided parameters.
.baselineOffset()
Moves text up or down relative to its baseline.
.bold()
Applies a bold style to text characters in a View.
.border()
Applies a border to a view, which can be customized with a specified style and width.
.draggable()
Gives a view the ability to be dragged.
.dropDestination()
Applies a destination to drop a draggable view.
.font()
Applies a specified font to text in a view.
.fontWeight()
Sets the font weight of the text in Text view.
.foregroundColor()
Sets the foreground color that is displayed in a view.
.frame()
Applies an invisible frame around the view with the specified sizes.
.italic()
Indicates that the font inside a view should have an italic style applied to it.
.kerning()
Adjusts the spacing size between text characters in a view.
.keyboardType()
Specifies the keyboard type to use for text entry.
.overlay()
Layers the specified views in front of another view.
.padding()
Applies spacing around a view.
.resizable()
Configures an image in a View to resize itself to fit the surrounding space of its parent container.
.scaledToFill()
Scales the view to fill its parent view while maintaining the original aspect ratio.
.scaledToFit()
Scales the view to fit its parent view while maintaining the original aspect ratio.
.strikethrough()
Applies a horizontal line through the middle of the text in a string.
.textFieldStyle()
Applies a specified style to a text field.
.tint()
Sets the tint color displayed in a view.
.tracking()
Adjusts the spacing of the characters in a Text view.
.underline()
Applies an underline style to text characters in a view.

All contributors

Contribute to Docs

Learn SwiftUI on Codecademy