Xcode 12.4/Swift Playgrounds: Code does not generate View

97 Views Asked by At

I am new to Xcode 12.4/Playgrounds, and am trying to get this code to run. So far, it doesn't generate the View object, and does not generate an error code either. Any ideas about what I'm doing wrong?

import SwiftUI
import PlaygroundSupport

struct ExampleView: View{
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .frame(width:200, height:200)
            Button(action: {
                })
            Text("Rotate")
        }
    };.padding(10)
}

PlaygroundPage.current.setLiveView(Example-View())
    .padding(100)
1

There are 1 best solutions below

0
On

Playgrounds is still kind of buggy (it's been so many years already)... anyway, you have a couple of errors:

Errors highlighted in code

  • Missing argument for parameter #1 in call: you're missing brackets {} after the Button that define what it looks like
  • Expected declaration: Modifiers like .padding() need to be inside the var body: some View. Move it to right after the VStack instead.
  • Cannot find 'Example' in scope: You misspelled ExampleView
  • There's no error yet, but you also can't attach .padding() to PlaygroundPage.current.setLiveView(ExampleView()). Modifiers always need to be inside a View.

Here's the fixed code:

import SwiftUI
import PlaygroundSupport

struct ExampleView: View {
    var body: some View {
        VStack {
            Rectangle()
                .fill(Color.blue)
                .frame(width: 200, height: 200)

            Button(action: {
                
            }) {
                Text("Rotate")
            }
        }
        .padding(10)
    }
}

PlaygroundPage.current.setLiveView(ExampleView())

Result:

Error-free code on left, blue square with button underneath in the live view on right