SwiftUI - How to use Modifier and Preview in Swift?

Note: This article is third of the multi-part SwiftUI tutorial series; if you haven’t read the first article (SwiftUI - Beginning with SwiftUI) click here, and if you haven’t read the second article (SwiftUI - Your First iOS App) click here.

If you are a beginner and you find it difficult to understand things written in this article. Feel free to ask questions on my Reddit page or Twitter. Remember, you can do it. ; )


Hey fellas! I hope you are keeping up with my articles and find it easy to follow; before we continue to our Second iOS App in SwiftUI. I thought it’s better to go through this article which is about “Modifiers and Previews”, this article is utmost important if you wanna get in-deep of SwiftUI as it covers some tips and tricks and essential things you need to know about SwiftUI.

If I miss anything you feel is essential, and this article should have it, please let me know in the comments section.

Exploring Modifiers

Exploring Modifiers is essential to understand the possibilities in SwiftUI better. SwiftUI has provided us with all the modifiers in one place. Navigate the Library button in your Xcode ( refer image below ) and press it.

Add Library Button Location.png

Upon the click of Library button, a popup will appear, make sure the 2nd tab is selected as shown in the image below.

Note: Your Canvas should be open while following this procedure.

Modifier PopUp.png

As shown in the image above, a list of modifiers is available for you to learn and modify your views the way you desire.

You can also Command + Click on your View in Canvas or in your Code Editor to modify or embed or group your Views ( Refer image shown below ). There are so many things you can do here without actually writing a single line of code.

Modifier Command Click.png

Exploring Previews

One of the best things about SwiftUI is its Previews, and I will tell you why.

Apple introduced Storyboard in iOS 5, and since the launch, it had many revolutionary updates and changes and will still be in use for many more years. Yet, as XIB faded as the years passed just like the "thee" of English language disappeared, Storyboard will also have its end. However, it's not going to be anytime soon; we need to keep updating ourself with the latest technologies. By disappeared I don't mean it is no longer available, but you will hardly see anyone using it.

Now, SwiftUI is here with a better rendering of your Views in Preview, with declarative API and Combine Framework; it is so far the best thing introduced by Apple. Rendering your application for multiple devices at once or debugging for dark mode and light mode without changing the settings, live rendering, and so much more, the way you debug your applications will completely change for good.

There are so many things you can do with your Preview, enormous possibilities waiting for you in the present and the future.

To demonstrate Previews, we will need our Text Rotator project from the previous tutorial. You can also download the project by clicking it here.

Now, let’s quickly add and change some few lines of code in our project.

Add the line mentioned below the degrees variable and above the body declaration.

var greetingText = "Hello Sir"

Now, replace the string parameter (“Hola !”) passed in your Text object inside VStack of the body declaration with the new variable we just declared greetingsText.

VStack {
            Text(greetingText)
            ....

In the second struct inside the static var previews declaration replace ContentView() with ContentView(greetingText: "Hello Swift") .

static var previews: some View {
    ContentView(greetingText: "Hello Swift")
}

Your code should look similar to the code mentioned below.

import SwiftUI

struct ContentView: View {
    
    @State private var degrees: Double = 0
    
    // 1
    var greetingText = "Hello Sir"
    
    var body: some View {
        VStack {
            // 2
            Text(greetingText)
                .font(.largeTitle)
                .foregroundColor(Color.green)
                .rotationEffect(Angle(degrees: degrees))
            
            Slider(value: $degrees, in: 0...360)
                .padding()
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        // 3
        ContentView(greetingText: "Hello Swift")
    }
}

Note: The preview shown in the Canvas is of the device selected from the simulator list next to the Run button. Feel free to change the device to anyone from the list. Refer to the image shown below.

Next, Replace the code in the second struct to make it match with the code mentioned below.

static var previews: some View {
        Group {
            ContentView(greetingText: "Hello Swift")
            
            ContentView(greetingText: "Hello Friend")
            .previewDevice("iPhone SE (2nd generation)")
        }
}

Your Canvas should now show two devices, first should be the one you have selected from the simulator list, and the second will be the iPhone SE (2nd generation).

If your Canvas doesn’t load the device, look for a Resume button on the top of Canvas.

Group mentioned in the above code helps you render more Devices with different configurations, but that’s not everything, you can change the default text size of the entire Device or debug your View in Dark mode.

Feel free to change the device from the list mentioned below, just replace the string with the string from below.

///     "iPhone 7"
///     "iPhone 7 Plus"
///     "iPhone 8"
///     "iPhone 8 Plus"
///     "iPhone SE"
///     "iPhone X"
///     "iPhone Xs"
///     "iPhone Xs Max"
///     "iPhone Xʀ"
///     "iPad mini 4"
///     "iPad Air 2"
///     "iPad Pro (9.7-inch)"
///     "iPad Pro (12.9-inch)"
///     "iPad (5th generation)"
///     "iPad Pro (12.9-inch) (2nd generation)"
///     "iPad Pro (10.5-inch)"
///     "iPad (6th generation)"
///     "iPad Pro (11-inch)"
///     "iPad Pro (12.9-inch) (3rd generation)"
///     "iPad mini (5th generation)"
///     "iPad Air (3rd generation)"

I know, right now you will feel like adding more devices in the Canvas but remember your machine may start lagging or even crash. Previews are so tremendous, but Apple will need to push a lot of updates to make our Previews seamless and less crashing. So, try to control your feelings and keep your Xcode updated.


Dark Mode

Before we proceed to the Dark Mode, we need to wrap our VStack inside the NavigationView. Refer the code below

var body: some View {
        NavigationView {

            VStack {
                Text(greetingText)
                    .font(.largeTitle)
                    .foregroundColor(Color.green)
                    .rotationEffect(Angle(degrees: degrees))
                
                Slider(value: $degrees, in: 0...360)
                    .padding()
            }
        }
    }

Next, let’s add a new modifier to our iPhone SE (Enter the dark mode).

// 1
            ContentView(greetingText: "Hello Friend")
                .previewDevice("iPhone SE (2nd generation)")
                .environment(\.colorScheme, .dark)

Woah! Your second device just entered the dark mode. Beautiful right? Press the Live Preview button next to your Device in Canvas to get a better hang of it.

Next, let’s add one more modifier to our iPhone SE.

.previewLayout(.fixed(width: 300, height: 300))

You can remove the line .previewDevice("iPhone SE (2nd generation)") as the device doesn't look like iPhone anymore. ; )

Preview Devices.png

What we did right now in this article is very limited, feel free to explore by yourself and let me know in a tweet. You can tweet me on the link mentioned here

There are so many more modifiers which we will be exploring in my upcoming articles, but for that, you will need to subscribe, and I'll keep you updated with my upcoming articles.

The next article is available here (SwiftUI - Your Second iOS App).

Click here to download the final project.

If you have any suggestions or questions, Feel free to connect me on Twitter. 😉

SwiftUI - Build Your Second iOS App in Swift : Part One

SwiftUI - Build Your First iOS App in Swift