How to use SwiftUI in a Playground

Share on facebook
Share on twitter
Share on pinterest

Xcode Playgrounds are a great way to test new ideas quickly and easily. You might have wondered if it is also possible to use SwiftUI views in a playground. And yes, it’s actually very straightforward 👇

Step 1: After you have created a playground, the first step is to import the necessary frameworks.

import UIKit
import PlaygroundSupport
import SwiftUI

Step 2: Next, you can create your SwiftUI view.

struct MyView: View {
    var body: some View {
        VStack {
            Text("Hello World!")
                .font(.title)
            Text("This a SwiftUI view")
        }
    }
}

Step 3: Before we can display this view, we need to convert it into an UIViewController. We do this by using an UIHostingController.

let viewController = UIHostingController(rootView: MyView())

Step 4: Finally, we use this view controller for the live view of our playground.

PlaygroundPage.current.liveView = viewController

If we run our playground now, we get our SwiftUI view displayed in a kind of preview simulator!

If you want to learn more about SwiftUI, make sure you follow us on Instagram and subscribe to our newsletter to not miss any updates, tutorials and tips!

Leave a Reply

Your email address will not be published. Required fields are marked *

small_c_popup.png

Covid-19 Forces you into quarantine?

Start Mastering swiftUI Today save your 33% discount