ViewModifier

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

.bold()
Applies a bold style to text characters in a View.
.italic()
Indicates that the font inside a view should have an italic style applied to it.
.underline()
Applies an underline style to text characters in a view.

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn SwiftUI on Codecademy