Skip to content

SwiftUI: exploring views and modifiers

In the introduction to SwiftUI post I mentioned views.

SwiftUI is all about views.

Remember the Hello World app?

import SwiftUI

struct ContentView: View {
    var body: some View {
        Text("Hello World")
    }
}

ContentView is the main view. Its job is to define which views compose our app.

In here, we have a single view, Text.

If you run this in Xcode, this is what the app will look like:

Notice the additional code after the ContentView struct: this is how we tell Xcode what to display in the preview panel on the right. It's not part of the app, but it's used in development.

A view can have modifiers.

Here's an example of a modifier of the Text view, font():

struct ContentView: View {
    var body: some View {
        Text("Hello World")
            .font(.largeTitle)
    }
}

This modifier takes the Text view we created and makes the font larger:

Different views can have different modifiers.

We've just seen the Text view so far, and that view has a number of modifiers you can use, including:

  • font() sets the default font for text in the view
  • background() sets the view background
  • foregroundColor() sets the color of the foreground elements displayed by the view
  • padding() pads the view along all edges

... and many more. In the case of Text you can check all the modifiers you can use in this page: https://developer.apple.com/documentation/swiftui/text-view-modifiers.

It's important to note that the modifier does not modify the existing view. It actually takes an existing view and creates a new view.

Why is this important? Because this fact causes the order of modifiers to matter.

Suppose you want to set the background of the Text view, and then add some padding to it.

Text("Hello World")
    .padding()
    .background(Color.blue)

Here's the result:

but if you invert the 2 modifiers, you get this result:

This is the consequence of modifiers returning a new view once they are applied, and not modifying the existing view.

→ Download my free Swift Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about swift: